-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay-5-3-sum.cpp
35 lines (35 loc) · 1.02 KB
/
Day-5-3-sum.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
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
int n = nums.size();
int K = 0;
vector<vector<int>> ans;
sort(begin(nums), end(nums));
for(int i=0; i<n; i++){
if(i>0 && nums[i]==nums[i-1]) continue;
int first = nums[i];
int req = K - first;
int j=i+1, k=n-1;
while(j<k){
int second = nums[j], third = nums[k];
int sum = second + third;
if(sum > req){
k--;
}else if(sum < req){
j++;
}else{
ans.push_back({first, second, third});
while(j<k){
if(nums[j]==second) j++;
else break;
}
while(j<k){
if(nums[k]==third) k--;
else break;
}
}
}
}
return ans;
}
};