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)
题目解析:
(1)我们将输入的数组进行排序。
(2)从第一开始进行遍历,那么需要后面的元素加起来是等于temp = -A[0],
因为后面的元素已经排好序了,如果后面元素的第一个与最后一个相加大于temp,那么我们应该把大的值调小,因此最后的end 需要减一。
同理当相加小于temp的时候,如果等于说明找到了。
(3)去除重复有两个地方。
外循环的时候,如果这个元素与前面的元素不同则处理,相同则不处理,进1。
内循环的时候也是相同的。
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
vector<vector<int> > threeSum(vector<int> &num) {
sort(num.begin(),num.end());
int len = num.size();
vector<vector<int>> triplets;
if(len < 3)
return triplets;
for(int i=0;i<len-2;i++)
{
while(i-1>=0 && i<len-2 && num.at(i-1) == num.at(i))
i++;
int remain = 0 - num.at(i);
int begin = i + 1;
int end = len -1;
while(begin < end)
{
int restemp = num.at(begin)+num.at(end);
if(restemp > remain)
end--;
if(restemp < remain)
begin++;
if(restemp == remain)
{
vector<int> temp;
temp.push_back(num.at(i));
temp.push_back(num.at(begin));
temp.push_back(num.at(end));
triplets.push_back(temp);
while(begin < end && num.at(begin+1) == num.at(begin))
begin = begin + 1;
while(begin < end && num.at(end-1) == num.at(end))
end = end - 1;
begin++;
}
}
}
return triplets;
}
void printArray(vector<vector<int> > &result)
{
int len = result.size();
for(int i=0;i<len;i++)
{
vector<int> temp = result.at(i);
cout << "[" ;
for(int j=0;j<(int)temp.size();j++)
{
cout << temp.at(j) << " ";
}
cout << "]" << endl;
}
}
int main(void)
{
vector<int> num;
num.push_back(-4);
num.push_back(-2);
num.push_back(1);
num.push_back(-5);
num.push_back(-4);
num.push_back(-4);
num.push_back(4);
num.push_back(-2);
num.push_back(0);
num.push_back(4);
num.push_back(0);
num.push_back(-2);
num.push_back(3);
num.push_back(1);
num.push_back(-5);
num.push_back(0);
vector<vector<int> > triplets = threeSum(num);
printArray(triplets);
system("pause");
return 0;
}