Leetcode_c++:3sum (015)

Source: Internet
Author: User

    • Topic
      Given an array S of n integers, is 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 is 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)
    • Complexity: O (n*n).
/ * First sort, then left and right clamp O (n*n) =sort (NLGN) +n*twopointers (n): O (n*n) * /#include <iostream>#include <vector>#include <algorithm>using namespace STD;classsolution{ Public: vector<vector<int> >Threesum ( vector<int>&num) { vector<vector<int> >RetintLen=num.size ();intTar=0;if(len<=2)returnRet Sort (Num.begin (), Num.end ()); for(intI=0; i<=len-3; i++) {//first Number:num[1]            intj=i+1;//second Number            intk=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; }        }returnRet }};intMain () { vector<int>NumintN,t; while(Cin>>n) { for(intI=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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.