-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1_Two_Sum.cpp
More file actions
31 lines (29 loc) · 805 Bytes
/
Copy path1_Two_Sum.cpp
File metadata and controls
31 lines (29 loc) · 805 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
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int diff, counter=0;
vector<int> ret;
ret.reserve(2);
map<int, int> ix;
for(int i = 0; i<nums.size(); i++){
diff = target-nums[i];
if(diff != nums[i]){
ix[nums[i]] = (i+1);
if(ix[nums[i]]>0 && ix[diff]>0){
ret.clear();
ret.emplace_back(i);
ret.emplace_back(ix[diff]-1);
return ret;
}
}
else{
ret.emplace_back(i);
counter++;
if(counter==2){
return ret;
}
}
}
return ret;
}
};