-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1_two_sum.cpp
43 lines (41 loc) · 1.03 KB
/
1_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
#include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;
// Brute force solution with O(n^2) time complexity
class Solution1 {
public:
vector<int> twoSum(vector<int> &nums, int target) {
vector<int> result;
int n = nums.size();
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (nums[i] + nums[j] == target) {
result.push_back(i);
result.push_back(j);
return result;
}
}
}
return result;
}
};
// Optimized solution with O(n) time complexity using hash map
class Solution2 {
public:
vector<int> twoSum(vector<int> &nums, int target) {
vector<int> result;
unordered_map<int, int> hash_map;
int n = nums.size();
for (int i = 0; i < n; i++) {
int complement = target - nums[i];
if (hash_map.find(complement) != hash_map.end()) {
result.push_back(hash_map[complement]);
result.push_back(i);
return result;
}
hash_map[nums[i]] = i;
}
return result;
}
};