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.
Note:
The solution set must not contain duplicate triplets.
Example:
Given array nums = [-1, 0, 1, 2, -1, -4], A solution set is: [ [-1, 0, 1], [-1, -1, 2] ]
给定一组数,找出所有三个元素相加为0的组合。但是注意排除元素重复组合,例如[-1,0,1]和[-1,-1,0]是同一个组合。
LeetCode第一题是 TwoSum问题,我用的暴力求解,两层for循环。但是这道题不能用暴力求解,三层for循环还得考虑重复元素问题,肯定会超时。
首先对数组从大到小排序,然后固定一个值,让另外两个数的和等于这个值的相反数。设立首尾两个指针,当和大于0就让右指针左移;和小于0就让左指针右移。
这道问题转化成了求两个数的和问题。
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> result;
if(nums.empty()) return result;//如果为空就直接返回
sort(nums.begin(),nums.end());//将nums中的数值从大到小排序
int i=0,j,k;
int a,b,c,r;
while(i<nums.size()-1){
j=i+1,k=nums.size()-1;
a=nums[i];
while(j<k){
b=nums[j],c=nums[k];
r=a+b+c;
if(r==0){result.push_back({nums[i],nums[j],nums[k]});}
if(r>=0) {while(nums[k]==c && k>j) k--;}//指针移动,并且排除重复元素
if(r<=0) {while(nums[j]==b && j<k) j++;}
}
while(nums[i]==a && i<nums.size()-1) i++;
}
return result;
}
};
K-sum问题还是挺多的,需要好好研究。学会使用排序。。。。