-
Notifications
You must be signed in to change notification settings - Fork 0
/
15. 3Sum.cpp
28 lines (27 loc) · 952 Bytes
/
15. 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
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
int n = nums.size();
sort(nums.begin(), nums.end());
vector<vector<int>> output;
for(int i=0; i<n-1; i++){
int low = i+1, high = n-1;
while(low < high){
if(nums[i] + nums[low] + nums[high] < 0){
low++;
}
else if(nums[i] + nums[low] + nums[high] > 0){
high--;
}
else{
output.push_back({nums[i], nums[low], nums[high]});
int tempIndex1 = low, tempIndex2 = high;
while(low < high && nums[low] == nums[tempIndex1]) low++;
while(low < high && nums[high] == nums[tempIndex2]) high--;
}
}
while(i+1 < n && nums[i] == nums[i+1]) i++;
}
return output;
}
};