[Leetcode] 3sum

Source: Internet
Author: User

3sum

Given an arraySOfNIntegers, are there elementsA,B,CInSSuch thatA+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.

 

For example, given array S = {-1 0 1 2-1-4}, a solution set is: (-1, 0, 1) (-1,-1, 2)

The most naive method is triple loop traversal, but the complexity of O (N ^ 3) must be TLE, Which is ineffective even if optimization is performed.
The key point is that after sorting the array, you can save a lot of repeated operations.
Reduce the complexity to O (N ^ 2) by using the "elements> = elements above ).
Class solution {public: vector <int> threesum (vector <int> & num) {vector <int> result; sort (Num. begin (), num. end (); For (vector <int>: size_type ST1 = 0; ST1 <num. size (); ST1 ++) {// If num [ST1] = num [st1-1], so in the case of num [st1-1], it has covered all the cases headed by num [ST1] If (ST1> 0 & num [ST1] = num [st1-1]) continue; vector <int >:: size_type st2 = ST1 + 1; vector <int >:: size_type st3 = num. size ()-1; while (st2 <st3) {// If num [st3] = num [st3 + 1], if num [st3 + 1] is at the end, the IF (st3 <num. size ()-1 & num [st3] = num [st3 + 1]) {st3 --; continue ;} int sum = num [ST1] + num [st2] + num [st3]; If (sum <0) st2 ++; else if (sum> 0) st3 --; else {vector <int> V; V. push_back (Num [ST1]); V. push_back (Num [st2]); V. push_back (Num [st3]); result. push_back (V); st2 ++; st3 -- ;}} return result ;}};

 

 

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.