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,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)
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 ;}};