Idea: 1. Sort arrays,
2. A traverses array a [0]... a [n-1];
3. when a = A [I], the following problems are: from a [I + 1] to a [n-1], B + C =-A (programming beauty 2.12: quickly finding two numbers that meet the conditions)
Note B = A [J] = A [I-1] C = A [k] = A [n-1]
If B + C <-a, J ++;
B + C>-a, j --;
B + c =-A records and J ++;
4. Another problem is unique triplet, so a = A [I] should judge whether it is equal to a [I-1]. If it is equal, the subquestion has been answered.
It is also necessary to determine whether B and C are the same as before. If they are the same, they have already been judged.
// 3sum. cpp: defines the entry point of the console application. // # Include "stdafx. H "# include <vector> # include <algorithm> # include <iostream> using namespace STD; bool mycomp (INT X1, int x2) {return X1 <X2 ;} class solution {public: vector <int> threesum (vector <int> & num) {sort (Num. begin (), num. end (), mycomp); int p1 = 0, P2 = 0; vector <int> res; If (Num. size () <3) return res; For (INT I = 0; I <num. size ()-2; I ++) {if (I> 0 & num [I] = num [I-1]) contin UE; int sum =-num [I]; P1 = I + 1; P2 = num. Size ()-1; while (P1 <P2) {// while (P1! = 1 & num [P1] = num [P1-1]) P1 ++; while (P1! = I + 1) & num [P1] = num [p1-1]) P1 ++; while (P2! = Num. size ()-1) & (P2> 0) & (Num [P2] = num [p2 + 1]) P2 --; If (P1> = P2) break; // cout <"(" <I <"," <P1 <"," <P2 <")" <Endl; if (Num [P1] + num [P2] = sum) {vector <int> tempv; tempv. push_back (Num [I]); tempv. push_back (Num [P1]); tempv. push_back (Num [P2]); Res. push_back (tempv); // cout <"**" <I <"," <P1 <"," <P2 <Endl; p2 --;} else if (Num [P1] + num [P2]> sum) {P2 --;} else if (Num [P1] + num [P2] <sum) {p1 ++ ;}}return res ;}}; int _ tmain (INT argc, _ tchar * argv []) {vector <int> test;/* test. push_back (-1); test. push_back (0); test. push_back (1); test. push_back (2); test. push_back (-1); test. push_back (-4); */test. push_back (0); test. push_back (0); test. push_back (0); test. push_back (0); test. push_back (0); test. push_back (0); solution SS; vector <int> res = ss. threesum (TEST); // cout <res. size () <Endl; For (INT I = 0; I <res. size (); I ++) {for (Int J = 0; j <res [I]. size (); j ++) cout <res [I] [J] <","; cout <Endl;} system ("pause "); return 0 ;}
[Leetcode] 3 Sum