leetcode_c++:3Sum(015)

来源:互联网 发布:卢松松博客php版下载 编辑:程序博客网 时间:2024/05/22 02:26
  • 题目
    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)
  • 复杂度: O(n*n)。

/* 先排序,然后左右夹逼 O(n*n)=sort(nlgn)+n*twopointers(n):O(n*n) */#include<iostream>#include<vector>#include <algorithm>using namespace std;class Solution{public:    vector<vector<int> > threeSum(vector<int> &num){        vector<vector<int> > ret;        int len=num.size();        int tar=0;        if(len<=2)            return ret;        sort(num.begin(),num.end());        for(int i=0;i<=len-3;i++){            //first number:num[1]            int j=i+1; //second number            int k=len-1; //third number            while(j<k){                if(num[i]+num[j]+num[k]<tar){                    ++j;                }else if(num[i]+num[j]+num[k]>tar){                    --k;                }else{                    vector<int> temp;                    temp.push_back(num[i]);                    temp.push_back(num[j]);                    temp.push_back(num[k]);                    ret.push_back(temp);                    ++j;                    --k;                    //follow 3 while can avoid the duplication                    while(j<k && num[j]==num[j-1])                        ++j;                    while(j<k && num[i]==num[i+1])                        ++i;                }            }            while ((i<len-3) && num[i] == num[i+1]) {                ++i;            }        }        return ret;    }};int main(){    vector<int> num;    int n,t;    while(cin>>n){        for(int i=0;i<n;i++){        cin>>t;        num.push_back(t );        }    Solution s;    vector<vector<int> > ret=s.threeSum(num);    for(vector<vector<int> >::iterator it=ret.begin();it!=ret.end();it++){        for(vector<int>::iterator it1=it->begin();it1!=it->end();it1++)            cout<<*it1<<" ";        cout<<endl;    }        return 0;    }}
0 0
原创粉丝点击