-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
42 lines (38 loc) · 996 Bytes
/
main.cpp
File metadata and controls
42 lines (38 loc) · 996 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
#include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;
class Solution
{
public:
vector<int> twoSum(vector<int>& nums, int target)
{
vector<int> answer(2);
unordered_map<int, int> complements;
for (int i = 0; i < (int)nums.size(); ++i)
{
int mapped = target - nums[i]; // mapped complement
if (complements.find(mapped) != complements.end())
{
answer[0] = complements[mapped];
answer[1] = i;
break;
}
complements[nums[i]] = i;
}
// for (auto el: complements)
// cout << "value: " << el.first << "; index: " << el.second << endl;
return answer;
}
};
int main()
{
vector<int> nums = {2, 7, 11, 15};
int target = 9;
Solution sol;
vector<int> answer = sol.twoSum(nums, target);
for (int el: answer)
cout << el << ", ";
cout << endl;
return 0;
}