In fact, the first thought wrong, the problem to think difficult, leading to no ideas, now a lot better.
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.
For example, given array S = [-1, 0, 1, 2,-1,-4], A solution set is: [[-1, 0, 1], [-1,-1, 2]]
The code is as follows: Algorithm complexity O (n^2)
1 classSolution {2 3 PublicList<list<integer>> Threesum (int[] num) {4 5arraylist<list<integer>> result =NewArraylist<list<integer>>();6 if(num = =NULL|| Num.length < 3) 7 returnresult;8 arrays.sort (num);9 intLastnum = num[0]-1;Ten for(inti = 0; I < num.length-2 && Num[i] <= 0; i++) { One if(Num[i]! =lastnum) { A result.addall (Find (num, i)); -Lastnum =Num[i]; - } the } - returnresult; - } - + PrivateArraylist<list<integer>> Find (int[] Array,intindex) { - + inti = index + 1; A intj = Array.length-1; at intLasti = Array[index]-1; - intLASTJ = Array[index]-1; - -Arraylist<list<integer>> Lists =NewArraylist<list<integer>>(); - - while(I <j) { in if(Array[i] + array[j] + array[index] = = 0) { - if(Array[i] = =Lasti) { toi++; +}Else if(Array[j] = =Lastj) { -j--; the}Else { *Lasti =Array[i]; $LASTJ =Array[j];Panax NotoginsengArraylist<integer> curlist =NewArraylist<integer>(); - Curlist.add (Array[i]); the Curlist.add (Array[j]); + Curlist.add (Array[index]); A Lists.add (curlist); thei++; +j--; - } $}Else if(Array[i] + array[j] + Array[index] > 0) { $j--; -}Else { -i++; the } - }Wuyi returnLists; the } -}
Note the points:
1, if you encounter duplicate numbers, then you can skip directly. Both the outer loop and the inner loop are all possible, because all are ordered, and if the same number is encountered, the same result must be produced.
2, the concrete implementation of the time directly let Lastnum equals the beginning of the number minus one, to ensure that the first number will not be skipped.
The core idea of the algorithm is to sort first. The complexity of this algorithm is O (N*LOGN). Next, look for each number in turn, each to find a number, the rest of the goal is to find the remaining number of 2 numbers, so that their sum of 0. Because of the order, the process algorithm complexity of finding two numbers can be reduced to O (n). That is, from both ends toward the middle. Each time if and greater than 0, it is indicated that in the case of the outer number determination, these two numbers and large, also want to make it smaller, let j--, and vice versa i++.
Resolution of 3sum issues