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]
]
解题思路:首先对数组进行排序,然后对数组进行遍历,每次把第i个数作为定值,在i以后的有序数组中,寻找使得加上第i个数等于0的两个数;寻找的策略贪心,首尾相加判断是否等于0 - nums[i] ;等于的操作是首尾各自中间移一位;如果大于,尾部向中间移一位;如果小于,首部向中间移一位;接下来,我们就要考虑数字中重复数字, 不考虑重复的数字数组集合里面就会出现相同的数组;考虑重复,就必须考虑i重复,和i以后有序数列中连续重复的数字,但又因为,单个数组中可以出现重复的数字,所以不用考虑i 与i以后的有序数列是否重复;所以我们只要在i的遍历中,最要相同的i就后移,直到不同的i;而在i以后寻找两个数时,与0-nums[i]相等时,两端向中间移动也要考虑重复数字,同理 大于0-nums[i]时,尾端移动时也要去除重复的数字,小于也是;
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> rs;
if(nums.size() < 2) return rs;
vector<int> ls(3, 0);
sort(nums.begin(),nums.end());
int i,start,end,pt;
int sum;
for (i = 0; i < nums.size() - 2; i++) {
start = i + 1;end = nums.size() - 1;
pt = 0 - nums[i];
while(start < end){
sum = nums[start] + nums[end];
if (sum == pt){
ls[0] = nums[i];
ls[1] = nums[start];
ls[2] = nums[end];
rs.push_back(ls);
while(nums[start] == nums[start + 1] && start < end) start++;
while(nums[end] == nums[end - 1] && start < end)end--;
start++;end--;
}
if(sum > pt) {while(nums[end] == nums[end - 1] && start < end)end--;end--;}
if(sum < pt) {while(nums[start] == nums[start + 1] && start < end)start++;start ++;}
}
while(i + 1 < nums.size()&&nums[i] == nums[i+1]) i++;
}
return rs;
}
};
运行结果: