-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path001_TwoSum.cpp
95 lines (86 loc) · 2.47 KB
/
001_TwoSum.cpp
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
# LeetCode 001
# Two Sum
// Beat 37.8% others
#include <map>
class Solution001 {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> result;
//Check boundary
if(1 >= nums.size())
return result;
//Put all values into map(sorted dictionary)
std::map<int, int> numsMap;
int size = nums.size();
for(int index = 0; index < size; index++)
numsMap[nums[index]] = index;
//Check to see if any index combinations existed
for(int firstIndex = 0; firstIndex < size - 1; firstIndex++)
{
int valueSec = target - nums[firstIndex];
std::map<int, int>::iterator posSec = numsMap.find(valueSec);
if(posSec != numsMap.end() && posSec -> second != firstIndex)
{
result.push_back(firstIndex);
result.push_back(posSec -> second);
break;
}
}
return result;
}
};
//Beat 67.1% after using 'unordered_map' rather than 'map'
class Solution002 {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> result;
//Check boundary
int size = nums.size();
if(1 >= size)
return result;
//Put all values into hash map(sorted dictionary)
std::unordered_map<int, int> numsMap;
for(int index = 0; index < size; index++)
numsMap[nums[index]] = index;
//Check to see if any index combinations existed
for(int firstIndex = 0; firstIndex < size - 1; firstIndex++)
{
int valueSec = target - nums[firstIndex];
std::unordered_map<int, int>::iterator posSec = numsMap.find(valueSec);
if(posSec != numsMap.end() && posSec -> second != firstIndex)
{
result.push_back(firstIndex);
result.push_back(posSec -> second);
break;
}
}
return result;
}
};
//Reference the answer provided by the website - LeetCode -- Beat 93.27% persons
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> result;
//Check boundary
int size = nums.size();
if(1 >= size)
return result;
//Put all values into hash map(sorted dictionary)
std::unordered_map<int, int> numsMap;
for(int index = 0; index < size; index++)
{
int valueFst = nums[index];
int valueSec = target - valueFst;
std::unordered_map<int, int>::iterator posSec = numsMap.find(valueSec);
if(posSec != numsMap.end())
{
result.push_back(posSec -> second);
result.push_back(index);
break;
}
numsMap[nums[index]] = index;
}
return result;
}
};