-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtwo_sum.cpp
59 lines (42 loc) · 1.29 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
52
53
54
55
56
57
58
59
#include <vector>
#include <iostream>
#include <unordered_map>
class Solution {
public:
std::vector<int> twoSum(std::vector<int>& nums, int target) {
std::vector<int> result;
for (int i = 0; i < nums.size(); i++) {
for (int j = i + 1; j < nums.size(); j++) {
if (nums[i] + nums[j] == target) {
result.push_back(i);
result.push_back(j);
return result;
}
}
}
return result;
}
// another solution with unordered map
std::vector<int> twoSum2(std::vector<int>& nums, int target) {
std::unordered_map<int, int> map;
std::vector<int> result;
for (int i = 0; i < nums.size(); i++) {
int complement = target - nums[i];
if (map.find(complement) != map.end()) {
result.push_back(map[complement]);
result.push_back(i);
return result;
}
map[nums[i]] = i;
}
};
int main() {
Solution solution;
std::vector<int> nums = {2, 7, 11, 15};
int target = 18;
std::vector<int> result = solution.twoSum(nums, target);
for (auto i : result) {
std::cout << i << std::endl;
}
return 0;
}