3Sum

来源:互联网 发布:do not tag 淘宝网 编辑:程序博客网 时间:2024/06/18 12:12

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.

    For example, given array S = {-1 0 1 2 -1 -4},    A solution set is:    (-1, 0, 1)    (-1, -1, 2)

和 Two Sum 类似,不过只需要在外面多一层循环遍历。以a=num[i]为最外层遍历。

然后b=num[i+1], c=num[len-1] 两侧逼近。

然后判断a+b+c=0,如果是,保存结果,然后b向后移动(c不需要动)。

注意因为不能有重复子集,所以需要判断当前的数字是否用过,这里采用的是判断和前一个用的num[i]是否相等来判定。


vector<vector<int> > threeSum(vector<int> &num){    vector<vector<int> > ans;    sort(num.begin(),num.end());    int len= num.size();    for(int i=0; i<len; i++)    {        if(i > 0 && num[i]==num[i-1])            continue;        int j= i+1,k=len-1;        while(j<k)        {            if(j>i+1&&num[j]==num[j-1])            {                j++;                continue;            }            if(k<len-1&& num[k]==num[k+1])            {                k--;                continue;            }            int sum = num[i] + num[j] + num[k];            if(sum==0)            {                vector<int> tmp;                tmp.push_back(num[i]);                tmp.push_back(num[j]);                tmp.push_back(num[k]);                ans.push_back(tmp);                j++;            }            else if(sum>0)                k--;            else                j++;        }    }    return ans;}


0 0