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)
The first thought must be three-layer loop traversal, time complexity O (n^3), but did the second Sum, feel instantaneous solvable, with the method of Hashtable:
Public list<list<integer>> THREESUM1 (int[] num) { list<list<integer>> lists = new Arraylist<> (); Hashmap<integer, integer> hash = new hashmap<> (); for (int i = 0; i < num.length; i++) { hash.put (num[i], i); } for (int i = 0, i < num.length; i++) {for (int j = i+1; J < Num.length; J + +) { if (Hash.get (0-NUM[I]-NUM[J) ) = null && num[i] <= num[j] && num[j] <= 0-num[i]-num[j]) { list<integer> List = new ARR Aylist<> (); List.add (Num[i]); List.add (Num[j]); List.add (0-num[i]-num[j]); Lists.add (list);}} } return lists; }
Time complexity should be in O (n^2), but unfortunately, the direct timeout! Looking at test instructions, need to solve in O (n)? After analysis, certainly not, at least also to O (NLGN). Well, it reminds me of the complexity of sorting, so it's better to control the array first.
First on the code:
Public list<list<integer>> threesum (int[] num) { list<list<integer>> lists = new ArrayList <> (); Arrays.sort (num); for (int i = 0; i < num.length-2; i++) { if (i = = 0 | | (i > 0 && num[i]! = num[i-1])) { int low = i+1, high = num.length-1, sum = 0-num[i]; while (Low < high) { if (num[low]+num[high] = = sum) { lists.add (arrays.aslist (Num[i], Num[low], Num[high])); C8/>while (Low < high && num[low] = = Num[low+1]) {low + +; } while (Low
First, control a variable a, linear traversal. At this point only need to find b,c meet b+c=-a can. Because it is sorted well, the rest can be found using the idea of two-point search to find B.C. Then solve (note to eliminate the repetitive solution!!!!) )
Leetcode-3sum (the sum of three numbers in the array is 0)