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.
For example, given array S = [-1, 0, 1, 2, -1, -4], A solution set is: [ [-1, 0, 1], [-1, -1, 2] ]
这个问题参考别人的代码,现在给出解决思路:
①首先对输入矩阵进行排序,变成从小到大或者从大到小的形式(在这里采用从小到大的形式)
②由于找到三个数的和为0,运用三个索引表示这三个数,i,j,k
③i表示第一个数,在这里对i进行[0,size-1]的循环
j=i+1表示大于i的第一个数,k=size-1,表示最大的数
分别计算i+j+k对应数值,将结果保存在total变量中,之后对total是否为0进行判断。
==0表示找到结果,<0说明j比较小,进行++,>0说明k比较大,进行--
④注意判断存在重复的情况,而题目明确要求不能输出重复的数列
代码如下:
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> ret;
int length = nums.size();
sort(nums.begin(),nums.end());
for(int i=0; i<length; i++)
{
while((i>0)&&(i<length)&&(nums[i]==nums[i-1]))
i++;
int j = i+1;
int k = length-1;
while(j<k)
{
int total = nums[i]+nums[j]+nums[k];
if(total==0)
{
vector<int> tmp(3);
tmp[0]=nums[i];
tmp[1]=nums[j];
tmp[2]=nums[k];
ret.push_back(tmp);
j++;
k--;
while(nums[j]==nums[j-1])
j++;
while(nums[k]==nums[k+1])
k--;
}
else if(total<0)
{
j++;
while(nums[j]==nums[j-1])
j++;
}
else
{
k--;
while(nums[k]==nums[k+1])
k--;
}
}
}
return ret;
}
};