题目

Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note: The solution set must not contain duplicate triplets.

1
2
3
4
5
6
7
For example, given array S = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]

题目大意:

在一个给出的序列中找出三个数,使三个数字的和加一起为0。

思路:

1首先先对数组排序

2枚举每个数,对每一个数a[i],若想条件成立,后面的两个数加起来都等于a[i]的负数,所以固定a[i]进行循环

3设立两个指针left,right,分别指向a[i]的下一个数和整个序列的最后一个数,因为数组已经排序,所以根据a[left]+a[right]的大小不断调整left right的位置。

4 需要注意的地方有因为不能重复,所以需要判断重复的元素情况,包括a[i]的重复情况 a[left]的重复情况a[right]的重复情况。

我的解法:

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
39
40
41
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> res;
sort(nums.begin(),nums.end());
int len= nums.size();
for(int i=0;i<len;i++)
{
int left =i+1;
int right =len-1;
int result= -nums[i];
while(left<right)
{
if(nums[left]+nums[right]>result)
{
right--;
}
else if (nums[left]+nums[right]<result)
{
left++;
}
else
{
vector<int> a;
int front =nums[left];
int end =nums[right];
a.push_back(nums[i]);
a.push_back(nums[left]);
a.push_back(nums[right]);
res.push_back(a);
while(left<right&&front==nums[left]) left++;
// 判断下一个left数是否重复,重复直接跳过。
while(left<right&&end==nums[right]) right--;
// 判断下一个right数是否重复,重复直接跳过。
}
}
while (i + 1 < nums.size() && nums[i + 1] == nums[i]) i++;
// 判断下一个a[i]数是否重复,重复直接跳过。
}return res;
}
};

参考了discuss的https://discuss.leetcode.com/topic/8107/share-my-ac-c-solution-around-50ms-o-n-n-with-explanation-and-comments方法。