您的位置:首页 > 其它

Two Sum —— leetcode

2016-09-04 18:51 351 查看
Given an array of integers, return indices of the two numbers such that they add up to a specific target.

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

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].


本题要求我们找出一串数字中的其中两个,它们相加后等于特定值。需注意以下几点:

1、由于本题数据量较大,用两层循环穷举所有情况将导致超时

2、由于数字可能有负数,所以不能直接用作下标

3、序列中可能有相同的数字

我设计的算法(复杂度为O(n))如下:

1、创建一个足够大的数组m,初始化为0,对于序列中的每个数字a,m[a + 10000]++;(避免负数)

2、对于序列中的每个数字a,判断target - a是否满足要求,若满足,a和target - a即为符合要求的数字

3、再遍历一遍所给序列,找到符合要求数字的下标

程序代码如下所示:

int m[20000];

class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> v;
memset(m,0,sizeof(m));

for(int i=0;i<nums.size();++i){
m[nums[i]+10000]++;
}

int a,b;
for(int i=0;i<nums.size();++i){
if(nums[i] == target - nums[i] && m[nums[i] + 10000] >= 2){
a = b = nums[i];
break;
}
else if(m[nums[i] + 10000] >= 1 && m[target - nums[i] + 10000] >= 1 && nums[i] != target - nums[i]){
a = nums[i];
b = target - nums[i];
break;
}
}

for(int i=0,j=0;i<nums.size() && j<2; ++i){
if(nums[i] == a || nums[i] == b){
v.push_back(i);
j++;
}
}

return v;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: