-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtwo_sum.cpp
More file actions
39 lines (27 loc) · 713 Bytes
/
two_sum.cpp
File metadata and controls
39 lines (27 loc) · 713 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
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> mp; // value -> index
for (int i = 0; i < nums.size(); i++) {
int remaining = target - nums[i];
if (mp.find(remaining) != mp.end()) {
return { mp[remaining], i };
}
mp[nums[i]] = i;
}
return {};
}
};
int main() {
Solution obj;
vector<int> nums = {2, 7, 11, 15};
int target = 17;
vector<int> result = obj.twoSum(nums, target);
cout << "Indices: ";
for (int index : result) {
cout << index << " ";
}
return 0;
}