Description
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].
AC代码
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> mp;
for(int i=0; i<nums.size(); i++) {
auto it = mp.find(target-nums[i]);
if(it!=mp.end()) {
return {it->second, i};
}
mp[nums[i]] = i; //程序实际上是从这里开始的,首先录入nums里的各个数,first是数值本身,second是下标
}
return {};
}
};
测试代码
int main() {
Solution s;
vector<int> a1{2, 7, 11, 15};
vector<int> res = s.twoSum(a1, 9);
cout<<"Result: ";
for(int i=0;i<res.size();i++) {
cout<<res[i]<<" ";
}
cout<<endl;
}
总结
这一题可以使用暴力解法,就是直接遍历所有的两个数的组合,算出它们的和,一旦遇到target,立马return。
另外一种比较常见的做法,就是利用map(也即是Python里的字典),第一遍遍历把各个数录入到map中,接着,进行第二遍的遍历,每遇到一个数x, 就看一下target-x在不在map里,如果在的话,就直接return二者的下标(second的值)。上面的"AC代码"即采用这种解法。