-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy path3Sum.cpp
More file actions
42 lines (40 loc) · 1.07 KB
/
3Sum.cpp
File metadata and controls
42 lines (40 loc) · 1.07 KB
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
// i j k
// -2 -2 -1 -1 0 0 0 2 2 2
// i j k
// 1 -1 -1 0
#include<bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>>ans;
if(nums.size()<=2)return ans;
sort(nums.begin(), nums.end());
for(int i=0;i<nums.size()-2;i++){
if(i!=0 && nums[i]==nums[i-1])continue;
int temp=0-nums[i];
int j=i+1, k=(int)nums.size()-1;
while(j<k){
if(nums[j]+nums[k]==temp){
ans.push_back({nums[i], nums[j], nums[k]});
while(j<k && nums[j+1]==nums[j])j++;
while(j<k && nums[k-1]==nums[k])k--;
j++;k--;
}
else if(nums[k]+nums[j]>temp){
k--;
if(k>j && k>i)while(nums[k+1]==nums[k])k--;
}
else if(nums[j]+nums[k]<temp){
j++;
if(j<k && j<nums.size())while(nums[j-1]==nums[j])j++;
}
}
}
return ans;
}
};
int main()
{
return 0;
}