题目
Given an array S of n integers, arethere elements a, b, c in S such that a + b + c = 0? Find allunique triplets in the array which gives the sum of zero.
Note: The solution setmust 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]]
思路
①直接遍历暴力搜索,太暴力了,不敢想;
②考虑到和为零的三个数,必然具有以下特点:第一,全为零或包含一个正数(或负数); 因此,在最外层循环中,只需要遍历所有非负数或非正数即可。第二,如果存在对某个数A,存在[A,B,C]、[A,D,E]两组解,必然有B
C++
vector<vector<int>>threeSum(vector<int>& nums) {
vector<vector<int>>output;
if(nums.size() < 3) return output;
sort(nums.begin(),nums.end());
unsignedi = 0, K = nums.size() - 1;
while(i < nums.size()){
if(nums[i] > 0) break;
unsignedj = i + 1;
while(j < K){
if(nums[K] > -2 * nums[i]) K--;
else break;
}
autok = K;
while(j < k){
autosum3 = nums[i] + nums[j] + nums[k];
if(sum3 == 0){
output.push_back({nums[i], nums[j], nums[k] });
j++;
k--;
}
elseif (sum3 < 0){
j++;
}
else{
k--;
}
}
i++;
while (i < nums.size()){
if(nums[i] == nums[i - 1]) {
i++;
}
else{
break;
}
}
}
vector<vector<int>>::iteratoriter = unique(output.begin(), output.end());
output.erase(iter,output.end());
returnoutput;
}