-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTwo_Sum.cpp
More file actions
42 lines (39 loc) · 1.16 KB
/
Two_Sum.cpp
File metadata and controls
42 lines (39 loc) · 1.16 KB
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
class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
int N = numbers.size();
vector<int> res;
if (N <=1) return res;
int i, j;
map<int ,vector<int>> mapping;
for (i=0;i<N;i++){
mapping[numbers[i]].push_back(i+1);
}
sort(numbers.begin(),numbers.end());
i = 0;
j = N-1;
int a, b;
while(i<j){
if (numbers[i] + numbers[j] == target){
if (numbers[i]==numbers[j]){
a = mapping[numbers[i]][0];
b = mapping[numbers[i]][1];
res.push_back(min(a,b));
res.push_back(max(a,b));
}
else{
a =mapping[numbers[i]][0];
b = mapping[numbers[j]][0];
res.push_back(min(a,b));
res.push_back(max(a,b));
}
return res;
}
else if (numbers[i] + numbers[j] > target)
j--;
else
i++;
}
return res;
}
};