思路
首先想到的肯定是双指针,但是双指针的复杂度比较高,使用hash结构能够有效的减少复杂度
方法
用map存放值以及下标,遍历一次数组即可(注意find找不到元素返回的是end()迭代器)
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> hash;
for (int i = 0; i < nums.size(); i++) {
if (hash.find(target - nums[i]) != hash.end()) {
return {
hash[target - nums[i]], i};
}
else hash[nums[i]] = i;
}
return {
};
}
};