-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path15.cpp
More file actions
33 lines (24 loc) · 893 Bytes
/
15.cpp
File metadata and controls
33 lines (24 loc) · 893 Bytes
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
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
sort(nums.begin(), nums.end()); //O(n log n)
vector<vector<int>> sols;
for(int i = 0; i < nums.size(); i++){
if(i > 0 && nums[i] == nums[i-1]) continue;
int sum = -nums[i];
int l = i+1; //left index
int r = nums.size()-1; //right index
while(l < r){
while(l < r && nums[l] + nums[r] > sum){
r--;
}
if(l < r && nums[l] + nums[r] == sum){
sols.push_back({nums[i], nums[l], nums[r]});
}
l++;
while(l < r && nums[l] == nums[l-1]) l++;
}
}
return sols;
}
};