leetcode-3Sum

来源:互联网 发布:youtube免费翻墙软件 编辑:程序博客网 时间:2024/06/05 20:33

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)
分析:先排序,按序取a,用two sum的方法求出b+c = -a;
class Solution {public:    vector<vector<int> > threeSum(vector<int> &num) {        int n = num.size();        vector<vector<int> > ret;        if(n < 3)return ret;        sort(num.begin(),num.end());        for(int i = 0; i < n-1; i++)        {            if((i > 0)&&(num[i] == num[i-1]))continue;            int a = 0-num[i];            int j = i+1;            int k = n-1;            while(k > j)            {                if(a == num[j]+num[k])                {                    vector<int> temp;                    temp.push_back(num[i]);                    temp.push_back(num[j]);                    temp.push_back(num[k]);                    ret.push_back(temp);                    k--;                    j++;                    while((num[j]==num[j-1])&&(j < n))j++;                    while((num[k]==num[k+1])&&(k > -1))k--;                }                else if(a > num[j]+num[k])j++;                else k--;            }                    }        return ret;    }};


0 0
原创粉丝点击