3Sum

来源:互联网 发布:淘宝口令红包怎么领 编辑:程序博客网 时间:2024/06/10 09:10


Given an array S of n integers, are there elementsa, 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,abc)
  • The solution set must not contain duplicate triplets.


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

0 0
原创粉丝点击