您的位置:首页 > 其它

[LeetCode]3Sum

2013-11-09 18:02 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:

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.

For example, given array S = {-1 0 1 2 -1 -4},

A solution set is:
(-1, 0, 1)
(-1, -1, 2)

思考:仿照在2Sum,增加一个循环遍历数组,复杂度O(n2)。一直纠结于是否存在O(nlogn)的解法?最初思路是在2Sum的基础上,二分搜索(0-num[i]-num[j])。未能解决搜索成功后i,j的变化。

class Solution {
public:
vector<vector<int> > threeSum(vector<int> &num) {
vector<vector<int> > res;
vector<int> ans;
sort(num.begin(),num.end());
int len=num.size();
for(int i=0;i<len-2;i++)
{
if(i&&num[i]==num[i-1]) continue;
int left=i+1;
int right=len-1;
while(left<right)
{
if(left>i+1&&num[left]==num[left-1])
{
left++;
continue;
}
if(right<len-1&&num[right]==num[right+1])
{
right--;
continue;
}
if(num[i]+num[left]+num[right]==0)
{
ans.clear();
ans.push_back(num[i]);
ans.push_back(num[left]);
ans.push_back(num[right]);
res.push_back(ans);
left++;
right--;
}
else if(num[i]+num[left]+num[right]>0) right--;
else left++;
}
}
return res;
}
};


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: