Two Sum ——经典的哈希表的题

时间:2021-09-02 21:20:44

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.

思路是循环一次,每次都判断当前数组索引位置的值在不在hashtable里,不在的话,加入进去,key为数值,value为它的索引值;在的话,取得他的key,记为n(此时n一定小于循环变量i),接下来再在hashtable中查找(target-当前数值)这个数,利用了hashtable中查找元素时间为常数的优势,如果找到了就结束,此处需要注意的是,如果数组中有重复的值出现,那么第二次出现时就不会加入到hashtable里了,比如3,4,3,6;target=6时,当循环到第二个3时,也可以得到正确结果。
        最终ac的代码如下:
class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
vector<int > res;
map<int,int> numMap;
map<int,int>::iterator iter;
int len=numbers.size();
for(int i=;i<len;i++)
{
iter=numMap.find(target-numbers[i]);
if(iter!=numMap.end())
{
res.push_back(iter->second);
res.push_back(i);
return res;
}
else
{
numMap[numbers[i]]=i;
}
} }
};