-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path3Sum.cpp
31 lines (30 loc) · 1017 Bytes
/
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
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
sort(nums.begin(), nums.end());
vector<vector<int>> ans;
for(int i = 0; i<nums.size(); i++){
if(i>0 && nums[i] == nums[i-1]) continue;
int j = i+1;
int k = nums.size() - 1;
while(j<k){
int sum = nums[i] + nums[j] + nums[k];
if(sum<0){
j++;
}
else if(sum > 0){
k--;
}
else{
vector<int> temp = {nums[i], nums[j], nums[k]};
ans.push_back(temp);
j++;
k--;
while( j<k && nums[j] == nums[j-1]) j++;
while( j<k && nums[k] == nums[k+1]) k--;
}
}
}
return ans;
}
};