-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1_TwoSum.cpp
63 lines (55 loc) · 1.27 KB
/
1_TwoSum.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<bits/stdc++.h>
using namespace std;
class Solution {
public:
/** @Two Pointer Approach O(n^2) **/
vector<int> twoSum(vector<int> &nums, int target) {
vector<int>res;
for (int i = 0; i < nums.size(); i++) {
for (int j = i + 1; j < nums.size(); j++) {
if (nums[i] + nums[j] == target) {
res.push_back(i + 1);
res.push_back(j + 1);
// break;
}
}
}
return res;
}
/*****@ HashMap Approach O(n) *****/
vector<int> twoSumEffi(vector<int> &numbers, int target) {
vector<int> res;
map<int, int> hmap;
hmap.clear();
for (int i = 0; i < numbers.size(); i++) {
hmap[numbers[i]] = i;
}
for (int i = 0; i < numbers.size(); i++) {
if (hmap.find(target - numbers[i]) != hmap.end()) {
if (i < hmap[target - numbers[i]]) {
res.push_back(i + 1);
res.push_back(hmap[target - numbers[i]] + 1);
break;
// return res;
}
if (i > hmap[target - numbers[i]]) {
res.push_back(hmap[target - numbers[i]] + 1);
res.push_back(i + 1);
break;
// return res;
}
}
}
return res;
}
};
int main() {
Solution s;
vector<int> nums = {1, 2, 3, 4, 5, 6, 1, 2, 0};
int target = 3;
// auto it = s.twoSum(nums, target);
auto it = s.twoSumEffi(nums, target);
for (auto x : it) {
cout << x << " ";
}
}