码迷,mamicode.com
首页 > 编程语言 > 详细

leetcode_c++:3Sum(015)

时间:2016-05-12 18:56:55      阅读:229      评论:0      收藏:0      [点我收藏+]

标签:

  • 题目
    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;
    }
}

leetcode_c++:3Sum(015)

标签:

原文地址:http://blog.csdn.net/mijian1207mijian/article/details/51345340

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!