-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
63 lines (55 loc) · 1.39 KB
/
main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include <iostream>
using namespace std;
class Solution {
public:
/**
* 哈希map1
* @param nums
* @param target
* @return
*/
vector<int> twoSum(vector<int> &nums, int target) {
for (int i = 0; i < nums.size(); i++) {
if (h.find(target - nums[i]) != h.end()) {
return {h[target - nums[i]], i};
}
h[nums[i]] = i;
}
return {};
}
/**
* 双指针扫描
* @param nums
* @param target
* @return
*/
vector<int> twoSum2(vector<int> &nums, int target) {
vector<pair<int, int>> pairs;
for (int i = 0; i < nums.size(); i++) {
pairs.push_back({nums[i], i});
}
sort(pairs.begin(), pairs.end());
int j = pairs.size() - 1;
for (int i = 0; i < pairs.size(); i++) {
while (i < j && pairs[i].first + pairs[j].first > target) {
j--;
}
if (i < j && pairs[i].first + pairs[j].first == target) {
return {pairs[i].second, pairs[j].second};
}
}
return {};
}
private:
unordered_map<int, int> h;
};
int main() {
Solution s;
vector<int> nums{2, 7, 11, 15};
int target = 9;
vector<int> result = s.twoSum(nums, target);
for (int j = 0; j < result.size(); ++j) {
cout << result[j] << " ";
}
return 0;
}