题目
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, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
解析
寻找两个数,这两个数之和为一个特定的数,可以采用
暴力搜索
,但是时间复杂度为O(n2)O(n^2)O(n2),Time Limit Exceeded。另一种方法,使用HashMap
,先建立数组中数值与其坐标位置之间的映射。HashMap是常数级的查找效率。这样,在遍历数组时,用target减去遍历到的数值,就是另一个需要的数字,然后再HashMap中查找其是否存在即可,但是查找到的数值不是遍历到的数值。整体过程:先遍历一遍数组,建立HashMap,然后再遍历一遍,开始查找,找到则记录下index。时间复杂度为O(n)O(n)O(n)
C++代码:
class Solution{
public:
vector<int> twoSum(vector<int>& nums, int target){
unordered_map<int, int> m;
vector<int> res;
// 遍历数组,建立HashMap
for (int i = 0; i < nums.size(); ++i ){
m[nums[i]] = i;
}
// 遍历数组,查找符合条件的数值
for (int i=0; i < nums.size(); ++i){
int t = target - nums[i];
if (m.count(t) && m[t]!=i){
res.push_back(i);
res.push_back(m[t]);
break;
}
}
returen res;
}
}
注意: unordered_map的用法