-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3sum.cpp
More file actions
37 lines (33 loc) · 1.08 KB
/
Copy path3sum.cpp
File metadata and controls
37 lines (33 loc) · 1.08 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
/*
* Problem statement :- https://leetcode.com/problems/3sum/description/
*/
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> res;
int n = nums.size();
sort(nums.begin(), nums.end());
for(int i = 0; i < n-2; i++) {
if(i && nums[i] == nums[i-1])
continue;
int target2sum = -nums[i];
int start = i+1, end = n-1;
while(start < end) {
if(nums[start] + nums[end] == target2sum){
vector<int> v = {nums[i], nums[start], nums[end]};
res.push_back(v);
start++, end--;
while(start <= n-1 && nums[start] == nums[start-1])
start++;
while(end >= 0 && nums[end] == nums[end+1])
end--;
} else if (nums[start] + nums[end] < target2sum) {
start++;
} else {
end--;
}
}
}
return res;
}
};