题目描述 :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)
分析:找出和等于定值的三个数,可以转化为找出两个数,使其和为一定值,只是这个定值在变化。
首先将数组从小到大排序,然后遍历一遍数组,对于第i个元素,接着找出从i+1到数组末尾之间的两个元素之和等于第i个元素的相反数。遍历过程中注意处理重复的元素以及下标范围。
以下是C++实现代码(耗时68ms):
class Solution {
public:
void getTwo(vector<int> &num,int a, int begin, int end,vector<vector<int>> &re) /*找出[begin,end]之间与a相加的和为0的两个数,满足则加入结果集中*/
{
int i = begin,j = end;
while( i < j)
{
if(num[i] + num[j] + a == 0)
{
vector<int> tmp;
tmp.push_back(a);
tmp.push_back(num[i]);
tmp.push_back(num[j]);
re.push_back(tmp);
while(i < j && num[i] == num[i+1]) /*跳过已处理过的相同的元素*/
i++;
while( i < j && num[j] == num[j-1])
j--;
i++;
j--;
}
else if(num[i] + num[j] + a < 0) /*若相加小于0,说明左边的加数太小,左下标加1*/
i++;
else /*若相加大于0,说明右边的加数太大,右下标减1*/
j--;
}
}
vector<vector<int>> threeSum(vector<int> &num) {
vector<vector<int> > re;
if(num.size() < 3 || num.empty())
return re;
sort(num.begin(),num.end());
//out1(num);
int j = num.size();
//getTwo(num,num[0],1,j ,re);
for(int i = 0; i != j-2; i++)
{
if(i > 0 && num[i] == num[i-1]) /*跳过重复处理过的元素*/
continue;
getTwo(num,num[i], i+1,j-1 ,re);
}
return re;
}
这是一类题型,找出和为定值的两个加数,相关内容可查阅《编程之美》之快速寻找满足条件的两个数