-
Notifications
You must be signed in to change notification settings - Fork 0
/
1. Two Sum
64 lines (53 loc) · 1.41 KB
/
1. Two Sum
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
60
61
62
63
64
class Solution {
public:
vector<int> twoSum1(vector<int>& nums, int target)
{
int size = int(nums.size()), count = 0;
for(int i = 0; i < size; ++i)
{
for(int j = i + 1; j < size; ++j)
{
if(nums[i] + nums[j] == target)
{
return {i, j};
}
}
}
return {-1, -1};
}
vector<int> twoSum2(vector<int>& nums, int target)
{
unordered_map<int, int> m;
int size = int(nums.size());
for(int i = 0; i < size; ++i)
{
auto &search = m.find(target - nums[i]);
if(search == m.end())
{
m[nums[i]] = i;
}
else if(search->second != i)
{
return {i, search->second};
}
}
return {-1, -1};
}
vector<int> twoSum(vector<int>& nums, int target)
{
unordered_map<int, int> m;
unordered_map<int, int>::const_iterator it;
for(int i = 0, size = int(nums.size()); i < size; ++i)
{
if((it = m.find(target - nums[i])) == m.end())
{
m[nums[i]] = i;
}
else
{
return {it->second, i};
}
}
return {};
}
};