-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1_Two_Sum.c++
More file actions
36 lines (34 loc) · 934 Bytes
/
1_Two_Sum.c++
File metadata and controls
36 lines (34 loc) · 934 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
32
33
34
35
36
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<pair<int,int>> temp;
for(int i=0; i<nums.size(); i++){
int index=i;
int value=nums[i];
pair<int,int>p=make_pair(value,index);
temp.push_back(p);
}
//sorting on the basis of value
sort(temp.begin(), temp.end());
//logic
int start=0;
int end= nums.size()-1;
vector<int>ans;
while(start<end){
int sum=temp[start].first + temp[end].first;
if(sum==target){
ans.push_back(temp[start].second);
ans.push_back(temp[end].second);
return ans;
}
else if(sum > target){
end--;
}
else{
//sum < target
start++;
}
}
return ans;
}
};