您的位置:首页 > 其它

15. 3Sum

2018-01-11 09:41 162 查看
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]
]

class Solution {
public:
void Sum3_helper(vector<int> &nums,int begin,int end,int target,int first,vector<vector<int>> &result)
{
int low=begin,high=end;

while(low<high)
{
if(high-low+1==2)
{
if(nums[low]+nums[high]==target)
{
vector<int> tmp;
tmp.push_back(first);
tmp.push_back(nums[low]);
tmp.push_back(nums[high]);
result.push_back(tmp);
}
return;
}
if(nums[low]+nums[high]>target) high--;
else if(nums[low]+nums[high]<target) low++;
else
{
if((low<end)&&(nums[low]==nums[low+1]))
{
low++;
continue;
}
if (high>begin&&(nums[high]==nums[high-1]))
{
high--;
continue;
}
vector<int> tmp;
tmp.push_back(first);
tmp.push_back(nums[low]);
tmp.push_back(nums[high]);
result.push_back(tmp);
low++;
}
}

}

vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> result;
if(nums.size()<3) return result;
int target=0;
sort(nums.begin(),nums.end());
for (int i=0; i<nums.size()-2;) {
int t=target-nums[i];
Sum3_helper(nums, i+1, nums.size()-1, t,nums[i],result);
int tmp=nums[i];
while(tmp==nums[i]&&i<nums.size()-2) i++;
}
return result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 3sum