leetcode-1-数组题-两数之和

题目

1.png

解法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
if (nums.size() <= 0)
return {-1, -1};

unordered_map<int, unsigned int> value_pos;

for(unsigned int i = 0; i < nums.size(); ++i){ // O(n)
if (value_pos.count(target - nums[i]) > 0){
return {value_pos[target-nums[i]], i};
}
value_pos[nums[i]] = i;
}

return {-1, -1};
}
};