This problem gives you an array that finds all three numbers that are equal to 0 and coexist in the list. Brute-force search would probably cost O (n^3) time, but if the array was ordered, it would be relatively simple to search, and the order would probably cost O (Nlog (n)) time, and ordered searches would only cost O (n^2), so the idea was this:
- Sorted first.
- Outer Loop I record the first number, the inner loop uses 2 pointer method, when Sum>0,tail moves left, sum < 0,head move right.
- When you encounter sum = Nums[i] + Nums[head] + Nums[tail], save three digits to the list and save the list to the outermost list2.
- Pay attention to the number repetition, I use the hashset to solve.
The code is as follows:
1 Public classSolution {2 PublicList<list<integer>> Threesum (int[] nums) {3List<list<integer>> List =NewArraylist<list<integer>>();4Set<integer> set =NewHashset<integer>();5 //Sort6 Arrays.sort (nums);7 for(inti = 0; i < nums.length-2; i++) {8 //judged there was no repetition. 9 if(!set.add (Nums[i]))Continue;Ten //if Nums[i] is greater than 0, there is no need to judge again . One if(Nums[i] > 0) Break; A intHead = i+1; - intTail = nums.length-1; - intLast =Nums[head]; the while(Head <tail) { - if(Head! = i+1 && Nums[head] = =Last ) { -head++; - Continue; + } - intsum = Nums[i] + Nums[head] +Nums[tail]; + if(Sum > 0) tail--; A Else if(Sum < 0) { atLast =Nums[head]; -head++; - } - Else { -List<integer> arrayList =NewArraylist<integer>(); - Arraylist.add (Nums[i]); in Arraylist.add (Nums[head]); - Arraylist.add (Nums[tail]); to List.add (arrayList); +Last =Nums[head]; -head++; thetail--; * } $ }Panax Notoginseng } - returnlist; the } +}
Leetcode (3Sum)