-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTwo Sum.cpp
More file actions
26 lines (25 loc) · 785 Bytes
/
Two Sum.cpp
File metadata and controls
26 lines (25 loc) · 785 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
class Solution {
public:
vector<int> twoSum(vector<int> &nums, int target)
{
//Key is the number and value is its index in the vector.
unordered_map<int, int> mymap;
vector<int> result;
int numToFind;
for (int i = 0; i < nums.size(); i++) // Adding the key and value to the map
mymap[nums[i]] = i;
for (int i = 0; i < nums.size(); i++)
{
numToFind = target - nums[i];
//NOW SEARCH IF numToFind is in the map
if((mymap.find(numToFind) != mymap.end()) && (i != mymap[numToFind])) // Ensures that the same index isn't summed up.
{
//It is found
result.push_back(i);
result.push_back(mymap[numToFind]);
return result;
}
}
return result;
}
};