LeetCode OJ:3Sum

来源:互联网 发布:seo原创文章怎么写 编辑:程序博客网 时间:2024/05/29 19:13

3Sum

 

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)
class Solution {public:    vector<vector<int> > threeSum(vector<int> &num) {        sort(num.begin(),num.end());        vector<vector<int>> ans;        vector<int> res;        int n=num.size();        for(int i=0;i<n;){            for(int p1=i+1,p2=n-1;p1<p2;){                int sum=num[i]+num[p1]+num[p2];                if(sum==0){                    res.clear();                    res.push_back(num[i]);                    res.push_back(num[p1]);                    res.push_back(num[p2]);                    ans.push_back(res);                    int t=num[p1];                    while(p1<p2&&num[p1]==t)                        ++p1;                }                else if(sum < 0)                    p1++;                else p2--;            }            int t=num[i];            while(i<n&&num[i]==t)                ++i;        }        return ans;    }};



0 0
原创粉丝点击