问题描述:Given an array nums
of n integers, are there elements a, b, c in nums
such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. 给定一个长度为n的数字串,是否存在三个元素a,b,c使得a+b+c=0,找出所有不同的元素组。不能包含重复的元素组。
样例:
Given array nums = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
思路:最粗暴的解法是 n³ 的复杂度,每层循环选中一个元素,判断和是否为0。
有一个复杂度为 n² 的算法:先将所有元素从小到大排好序,然后选取一个元素 i,另外两个元素 j,k 初始时在 i 之后的数组的两端,然后移动 j,k 的位置使得三者的和为0(其中 j 只向右移,k只向左移)。C++实现代码如下:
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>>result;
if(nums.size()<=2) return result;
sort(nums.begin(),nums.end());
for(int i=0;i<nums.size()-2;++i){
if(nums[i]>0) break;
if(i>0&&nums[i-1]==nums[i]) continue;
for(int j=i+1,k=nums.size()-1;j<k;){
int a=nums[j],b=nums[k];
int value=nums[i]+a+b;
if(value==0){
vector<int>temp;
temp.push_back(nums[i]); temp.push_back(nums[j]); temp.push_back(nums[k]);
result.push_back(temp);
while(b==nums[--k]);
while(a==nums[++j]);
}
else if(value>0){
--k;
}
else{
++j;
}
}
}
return result;
}
};