LeetCode-15. 3Sum
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] ]
解题:此题要求解数组中三个数,且这三个数的和为0,为避免重复的情况我们可以先将元素进行排序,然后让a遍历每一个元素,固定a,同时两头缩进寻找b和c。注意当出现相同解的情况要跳过。
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
sort(nums.begin(),nums.end());
vector<vector<int>> ans;
for(int i=0;i<nums.size();++i)
{
if(i>0&&nums[i]==nums[i-1])
continue;
int l=i+1,r=nums.size()-1;
while(l<r)
{
int s=nums[i]+nums[l]+nums[r];
if(s>0)--r;
else if(s<0)++l;
else
{
ans.push_back(vector<int>{nums[i],nums[l],nums[r]});
while(nums[l]==nums[l+1])++l;
while(nums[r]==nums[r-1])--r;
++l;
--r;
}
}
}
return ans;
}
};