-
Notifications
You must be signed in to change notification settings - Fork 0
/
two_sum.cpp
51 lines (45 loc) · 1.32 KB
/
two_sum.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
#include <vector>
#include <unordered_map>
class Solution {
public:
// Brute Force
vector<int> twoSum(vector<int>& nums, int target) {
int n = nums.size();
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
if (nums[i] + nums[j] == target) {
return {i, j};
}
}
}
return {}; // No solution found
}
// using one-pass hash-map
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> umap;
int n = nums.size();
for (int i = 0; i < n; i++) {
int remaining_val = target - nums[i];
if (umap.count(remaining_val) == 1) {
return {i, umap[remaining_val]};
}
umap[nums[i]] = i;
}
return {};
}
// using two-pass hash-map
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> umap;
int n = nums.size();
for (int i = 0; i < n; i++) {
umap[nums[i]] = i;
}
for (int i = 0; i < n; i++) {
int complement = target - nums[i];
if (umap.count(complement) == 1 && umap[complement] != i) {
return {i, umap[complement]};
}
}
return {};
}
};