-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy path3 sum problem
33 lines (33 loc) · 1007 Bytes
/
3 sum problem
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<vector<int>> threeSum(vector<int>& nums)
{
vector<vector<int>> ans;
int n = nums.size();
sort(nums.begin(), nums.end());
for(int i=0; i<n-2; i++)
{
int left = i+1, right = n-1;
while(left < right)
{
int s = nums[i] + nums[left] + nums[right];
if(s < 0) left++;
else if(s > 0) right--;
else
{
vector<int> t(3);
t[0] = nums[i];
t[1] = nums[left];
t[2] = nums[right];
ans.push_back(t);
left++;
right--;
while(left < right && nums[left] == t[1]) left++;
while(left < right && nums[right] == t[1]) right--;
}
}
while(i < n-2 && nums[i] == nums[i+1]) i++;
}
return ans;
}
};