-
Notifications
You must be signed in to change notification settings - Fork 3
/
3sum.cpp
42 lines (38 loc) · 1.09 KB
/
3sum.cpp
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<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int> >ans;
sort(nums.begin(),nums.end());
int len = nums.size();
for(int i=0;i<len;i++)
{
int sum = -nums[i];
if(i > 0 && nums[i] == nums[i-1])
continue;
int lo = i+1;
int hi = len-1;
while(lo<hi)
{
if(nums[lo] + nums[hi] == sum)
{
vector<int>t;
t.push_back(nums[i]);
t.push_back(nums[lo]);
t.push_back(nums[hi]);
ans.push_back(t);
while(lo<hi && nums[lo] == nums[lo+1])
lo++;
while(lo<hi && nums[hi] == nums[hi-1])
hi--;
lo++;
hi--;
}
else if(nums[lo] + nums[hi] < sum)
lo++;
else
hi--;
}
}
return ans;
}
};