-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode1.cpp
More file actions
33 lines (33 loc) · 762 Bytes
/
LeetCode1.cpp
File metadata and controls
33 lines (33 loc) · 762 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
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<pair<int,int>> v;
vector<int> ans;
for(int i=0; i<nums.size(); i++)
{
v.push_back({nums[i],i});
}
sort(v.begin(), v.end());
int l = 0;
int r = nums.size()-1;
while(l<r)
{
int m = v[l].first+v[r].first;
if(m == target)
{
ans.push_back(v[l].second);
ans.push_back(v[r].second);
break;
}
else if(m > target)
{
r--;
}
else if(m < target)
{
l++;
}
}
return ans;
}
};