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