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] ] 一个是暴力求解,三层循环,复杂度是三次方O(n3),太耗时。另一种,利用两数之和的求解方法,拆为一个数,和两个数,两数之和是0-num1, 再按两数求解的方式,另外要求不能重复,就用set来存储,最后给vector,若嫌代价大,那就自己检测,但貌似未必比set来的有效率。
vector<vector<int>> threeSum(vector<int>& nums) {
set<vector<int>> result;
sort(nums.begin(), nums.end());
for(int i=0; i<nums.size();++i){
if(nums[i]>0)
break;
if(k>0&&nums[i] == nums[i-1])
contimue;
int target=0-nums[i];
int j=i+1;
int k=nums.size()-1;
while(j<k)
if(num[j)+nums[k]==target){
result.insert({nums[i],nums[j],nums[k]});
++j;--k;
}
else if(nums[j]+nums[k]<target)
++j;
else
--k;
}
return vector<vector<int>>(result.begin(),result.end());
}