leetcode 3sum

数组的3Sum

3Sum

解题
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:
Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
The solution set must not contain duplicate triplets.
For example, given array S = {-1 0 1 2 -1 -4},

A solution set is:
(-1, 0, 1)
(-1, -1, 2)

题目大意:给定数组,求出数组中三个数的和为0的所有子数组,要求子数组的索引按递增排列。

解题思路:
(1)先将数组排序
(2)固定好第一个数字(外层循环)
(3)第二步就是求2Sum的过程,但需要注意的是判断重复,此处的重复指的是数字重复

先去重,再判断是否满足条件,这样可以减少一次去重(最后一个数)

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
42
43
44
45
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int> > result;

if(nums.size() < 3)
return result;

//先排序
sort(nums.begin(), nums.end());

for(int i = 0; i < nums.size() - 2; i++){
//第一个数的去重
if(i > 0 && nums[i - 1] == nums[i])
continue;

//two sum
int target = -nums[i];
int start = i + 1;
int end = nums.size() -1;
while(start < end){
//跳过计算过的重复的选项(此处去重时,start>i+1)
if(start > i +1 && nums[start - 1] == nums[start]){
start++;
continue;
}

if(nums[start] + nums[end] < target)
start++;
else if(nums[start] + nums[end] > target)
end--;
else{
vector<int> solution;
solution.push_back(nums[i]);
solution.push_back(nums[start]);
solution.push_back(nums[end]);

result.push_back(solution);
start++;
}
}
}
return result;
}
};

另一种解法:
先判断是否满足条件,满足条件,再去重(三次)
http://bangbingsyb.blogspot.com/2014/11/leetcode-3sum.html