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