首页 > 其他 > 详细

Two Sum

时间:2015-09-30 23:22:05      阅读:619      评论:0      收藏:0      [点我收藏+]

题目:

  Given an array of integers, find two numbers such that they add up to a specific target number.

  The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

  You may assume that each input would have exactly one solution.

  Input : numbers={2, 7, 11, 15}, target=9
  Output : index1=1, index2=2

 

思路:

  建立一个长度为 target 大小的数组 index 作为哈希表,初值为0,key 是合成 target 的值, value 是 key 在 nums 中的下标,遍历 nums 数组,做如下操作:

  1. 若 nums[i] > target , continue
  2. 若 index[target - nums[i]] == 0 , index[nums[i]] = i + 1 , continue 记录下比 target 小的数的下标,用于之后定位
  3. 否则,index[target - nums[i]] 就是 index1 ,i +1 就是 index2

  基于上述思路的代码如下:

 

技术分享
 1 int* twoSum(int* nums, int numsSize, int target) {
 2     int i;
 3     int * index  = calloc(target + 1, sizeof(int));
 4     int * result = malloc(sizeof(int) * 2);
 5     
 6     for (i = 0; i < numsSize; ++i) {
 7         if (nums[i] > target)
 8             continue;
 9         if (index[target - nums[i]] == 0) {
10             index[nums[i]] = i + 1;
11             continue;
12         }
13         result[0] = index[target - nums[i]];
14         result[1] = i + 1;
15         break;
16     }
17     free(index);
18     return result;
19 }
输入数组非负

   

  然而这是错误的,因为输入的数组可能存在负数,我们无法找到下标为负数的数组,因此对原方法做修正:遍历一遍数组,记录最小值 minNum ,对哈希表的所有 key 做minNum 大小的偏移,那么 target 需要做 2*minNum 大小的偏移,基于此思路得到正确代码如下:

 

技术分享
 1 /**
 2  * Note: The returned array must be malloced, assume caller calls free().
 3  */
 4 int* twoSum(int* nums, int numsSize, int target) {
 5     int i, min = nums[0], first;
 6     int * index;
 7     int * result = malloc(sizeof(int) * 2);
 8     
 9     for (i = 1; i < numsSize; ++i) {
10         if (min > nums[i])
11             min = nums[i];
12     }
13     target -= 2 * min;
14     index = calloc(target + 1, sizeof(int));
15     for (i = 0; i < numsSize; ++i) {
16         first = nums[i] - min;
17         if (first > target)
18             continue;
19         if (index[target - first] == 0) {
20             index[first] = i + 1;
21             continue;
22         }
23         result[0] = index[target - first];
24         result[1] = i + 1;
25         break;
26     }
27     free(index);
28     return result;
29 }
4ms AC

 

Two Sum

原文:http://www.cnblogs.com/YaolongLin/p/4849407.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!