leetcode-15-3sum

题目

给定一个数组,寻找3个数和为0的所有组合。

分析

略(双指针实现)

C++代码实现

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
38
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> res;
vector<int> num;
sort(nums.begin(), nums.end());
for(int i = 0; i < nums.size(); i++)
{
int front = i+1;
int end = nums.size() - 1;
while(front < end)
{
if(nums[i] + nums[front] + nums[end] == 0)
{
num.push_back(nums[i]);
num.push_back(nums[front]);
num.push_back(nums[end]);
res.push_back(num);


//Rolling the front pointer to the next different number forwards
while(front < end && nums[front] == num[1]) front++;

//Rolling the back pointer to the next different number backwards
while(front < end && nums[end] == num[2]) end--;
num.clear();
}
else if(nums[i] + nums[front] + nums[end] < 0) front++;
else end--;

//过滤掉重复元素(过滤掉第一个相同的元素)
while(i+1 <= nums.size() && nums[i+1] == nums[i])
i++;
}
}
return res;
}
};