-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtwo_sum.cpp
More file actions
44 lines (33 loc) · 860 Bytes
/
two_sum.cpp
File metadata and controls
44 lines (33 loc) · 860 Bytes
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
#include <iostream>
#include <vector>
#include <map>
using namespace std;
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
map<int, int> seen;
vector<int> result;
for (int i = 0; i < nums.size(); ++i) {
int temp = target - nums[i];
if (seen[temp]) {
result.push_back(seen[temp] - 1);
result.push_back(i);
break;
}
seen[nums[i]] = i + 1;
}
return result;
}
};
int main() {
Solution solution;
vector<int> nums = {2, 7, 11, 15};
int target = 9;
vector<int> result = solution.twoSum(nums, target);
if (!result.empty()) {
cout << "[" << result[0] << "," << result[1] << "]\n";
} else {
cout << "No valid pair found.\n";
}
return 0;
}