-
Notifications
You must be signed in to change notification settings - Fork 1
/
3Sum.cpp
33 lines (30 loc) · 1 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
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
std::sort(nums.begin(),nums.end());
vector<vector<int >> res;
for(int i=0;i<nums.size();i++){
int target=-nums[i];
int front=i+1;
int back=nums.size()-1;
while(front<back){
int sum=nums[front]+nums[back];
if(sum>target)
back--;
else if(sum<target)
front++;
else{
vector<int> tri(3,0);
tri[0]=nums[i];
tri[1]=nums[front];
tri[2]=nums[back];
res.push_back(tri);
while(front<back&&nums[front]==tri[1]) front++;
while(front<back&&nums[back]==tri[2]) back--;
}
while(i+1<nums.size()&&nums[i+1]==nums[i]) i++;
}
}
return res;
}
};