[Problem]
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)
[Analysis]
The main point of this question is the two requirements in the note, which can be sorted out. After sorting, first put forward a number and then use 2Sum to solve. Note that you should skip the numbers that have been used. The overall complexity is O (NLOGN) + O (n*n) = O (n*n).
[Solution]
Importjava.util.ArrayList;Importjava.util.Arrays;Importjava.util.List; Public classSolution { PublicList<list<integer>> Threesum (int[] num) {List<List<Integer>> solution =NewArraylist<list<integer>>(); if(Num.length < 3) { returnsolution; } arrays.sort (num); inttarget = 0; for(inti = 0; i < num.length-2; i++) { if(i > 0 && num[i] = = Num[i-1]) { Continue;//If current value is already tested as the first element, skip; } //Do 2Sum intHead = i + 1; intTail = num.length-1; while(Head <tail) { if(Head > i + 1 && num[head] = = Num[head-1]) {head++; Continue;//If current value is already tested as the second, skip; } if(Tail < num.length-1 && Num[tail] = = Num[tail + 1]) {tail--; Continue;//similar test for the third element } intsum = Num[i] + Num[head] +Num[tail]; if(Sum = =target) {Solution.add (NewArraylist<integer>(Arrays.aslist (Num[i], Num[head], num[tail])); Head++; Tail--; } Else if(Sum >target) {Tail--; } Else{Head++; } } } returnsolution; }}
Leetcode #15 3Sum (M)