题目链接
https://leetcode.com/problems/two-sum/
思路
用unordered_map将序列hash,然后对于每个数,O(1)的去查找
时间复杂度:O(N)
代码
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> mm;
vector<int> ans;
for (auto x : nums) mm[x]++;
for (auto x : nums) {
int y = target - x;
if (x == y) {
if (mm[x] > 1) {
for (int i = 0; i < nums.size(); i++) {
if (nums[i] == x) {
ans.push_back(i);
if (ans.size() == 2) return ans;
}
}
}
} else {
if (mm[y])
for (int i = 0; i < nums.size(); i++)
if (nums[i] == x || nums[i] == y) {
ans.push_back(i);
if (ans.size() == 2) return ans;
}
}
}
return ans;
}
};