###### leetcode 015 —— 3Sum

Given an array S of n integers, are there elements abc in S such that a + b + c = 0? Fi
nd 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)

class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> res;
int n = nums.size();
if (n < 3)	return res;
sort(nums.begin(), nums.end());
for (int i = 0; i < n - 2; i++){
if (i>0 && nums[i] == nums[i - 1])//序列nums是递增的，所以nums[i]能产生的组合总是<= nums[i-1]
continue;
int target = 0 - nums[i];
int start = i+1;
int end = n-1;
while (start < end){
int sum = nums[start] + nums[end];
if (sum == target){
vector<int> tmp;
tmp.push_back(nums[i]);
tmp.push_back(nums[start]);
tmp.push_back(nums[end]);
//cout << nums[i] << ' ' << nums[start] << ' ' << nums[end] << endl;
res.push_back(tmp);
while (start < end&&nums[start] == nums[start + 1])
start++;
while (start < end&&nums[end] == nums[end - 1])
end--;
start++;  //继续往中间搜索
end--;

}
else if (sum < target)
start++;
else
end--;

}

}
return res;

}
};

#### [LeetCode] 015. 3Sum (Medium) (C++/Java/Python)

2015-03-03 18:53:30

#### LeetCode 15 3Sum (C,C++,Java,Python)

2015-05-09 21:06:57

#### leetcode--ksum问题--3sum

2016-07-17 22:08:28

#### 【LeetCode】3Sum 解题报告

2014-10-30 16:00:34

#### leetcode 3sum c语言

2015-07-10 09:59:31

#### [LeetCode] 3Sum分析与C/C++解法

2016-03-08 21:23:37

#### 【leetcode】3SUM python实现

2016-06-03 13:08:40

#### LeetCode 16 3Sum Closest(C,C++,Java,Python)

2015-05-09 22:26:02

#### [leetcode javascript解题]3Sum

2016-12-20 15:39:24

#### [LeetCode]3Sum

2013-11-24 11:20:37

## 不良信息举报

leetcode 015 —— 3Sum