Given an array S of n integers, are there elements abc in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note:

  • Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
  • The solution set must not contain duplicate triplets.

思路:首先大循环第一个数,从第一个数之后首尾指针向中间夹逼,时间复杂度O(n2)。需要注意跳过重复的数字。

class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
int size = nums.size();
if(size < ) return result; sort(nums.begin(), nums.end());
find(nums, , size-, -nums[]);
for(int i = ; i < size-; i++){
if(nums[i]!=nums[i-]) find(nums, i+, size-, -nums[i]);
}
return result;
}
void find(vector<int>& nums, int start, int end, int target){
int sum;
while(start<end){
sum = nums[start]+nums[end];
if(sum == target){
item.clear();
item.push_back(-target);
item.push_back(nums[start]);
item.push_back(nums[end]);
result.push_back(item);
do{
start++;
}while(start!= end && nums[start] == nums[start-]);
do{
end--;
}while(end!=start && nums[end] == nums[end+]);
}
else if(sum>target){
do{
end--;
}while(end!=start && nums[end] == nums[end+]);
}
else{
do{
start++;
}while(start!= end && nums[start] == nums[start-]);
}
}
} private:
vector<vector<int>> result;
vector<int> item;
};
05-11 17:20