-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path15. 3Sum ( Leetcode )
36 lines (32 loc) · 1.02 KB
/
15. 3Sum ( Leetcode )
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
vector<vector<int>> threeSum(vector<int>& nums)
{
int size = nums.size();
vector<vector<int>> ans;
sort(nums.begin(), nums.end());
for(int i = 0; i < size; i++)
{
int target = -1 * nums[i];
int start = i+1, end = size-1;
while(start < end)
{
if(nums[start] + nums[end] == target)
{
ans.push_back({nums[i], nums[start], nums[end]});
while(start < end && nums[start] == nums[start + 1]) start++;
while(start < end && nums[end] == nums[end - 1]) end--;
start++;
end--;
}
else if(nums[start] + nums[end] > target)
{
end--;
}
else
{
start++;
}
}
while(i+1 < size && nums[i+1] == nums[i]) i++;
}
return ans;
}