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].
UPDATE (2016/2/13):
The return format had been changed to zero-based indices. Please read the above updated description carefully.
s思路:
1. 简单粗暴的方法:双重for循环,看两个数相加是否等于target, 这样复杂度o(n^2)。另外一种思路,是用unordered_map,把所有数存在hashtable,然后遍历每个数,都看target-nums[i]这个数是否也在hashtable中。这样,复杂度就是o(n)。
2. 为什么用hashtable速度可以提高一个量级呢?首先,用hashtable空间复杂度从o(1)->o(n),是用空间换取时间。为什么空间可以换取时间呢?这就是hashtable的妙,可以o(1)的查询时间,所以可以把遍历变成查询,从而减低复杂度!
3. 这个题,自己做又忽略了一个大bug。即:重复。例如:[3,2,4], target=6.则:6-3=3,这个值等于3. 或[2,4,4,7], target=8, nums内有重复。所以要排除这种情况!
4. 如何排除?不能把所有数都存在hashtable之后,再去一个一个检查,而应该边存,边检查,即:把两个for合并成一个,让存和检查交叉起来,而不是完全分开。为什么这样可以解决重复?如果同时把两个重复的数都放hashtable,则第二个坐标会把第一个坐标覆盖,所以不能先放完再检查,但是我们现放一个,target-第二个如果等于第一个,我们就可以直接返回这两个坐标,而不用把第二个存入;
//bug1:[3,2,4], target=6.则:6-3=3,这个值也等于3.
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
//
vector<int> res(2,0);
unordered_map<int,int> mm;
for(int i=0;i<nums.size();i++){
mm[nums[i]]=i;
}
for(int i=0;i<nums.size();i++){
if(mm.count(target-nums[i])){
res[0]=i;
res[1]=mm[target-nums[i]];
break;
}
}
return res;
}
};
//解决重复的bug!
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
//
vector<int> res(2,0);
unordered_map<int,int> mm;
for(int i=0;i<nums.size();i++){//合并两个for,而且先检查,再保存!
if(mm.count(target-nums[i])){
res[0]=i;
res[1]=mm[target-nums[i]];
break;
}
mm[nums[i]]=i;
}
return res;
}
};