-
Notifications
You must be signed in to change notification settings - Fork 0
/
cppsolution2.cpp
37 lines (26 loc) · 976 Bytes
/
cppsolution2.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
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
//Map of compliments and their locations w/ iterator
map<int, int> m;
map<int, int>::iterator it = m.begin();
int complement = 0;
//The vector we will return
vector<int> vec;
for(int i = 0; i<nums.size(); i++){
//Value of the target minus current value of nums
complement = target-nums.at(i);
//Iterates through m looking for key complement O(n)
it = m.find(nums.at(i));
//If iterator doesn't hit end of map - return locations
if(it != m.end()){
vec.push_back(i);
vec.push_back(it->second);
return vec;
}//end if
//Add complement as key and location as value
m.insert(pair<int,int>(complement, i));
}//end for
return vec;
}//end function
};//end class