The title comes from the 15th question of Leetcode
Given the array s of n integers, is there an element a,b,c in s that makes A + B + c = 0? Finds all the unique triples in the array, and their sum is zero.
Note: The solution set cannot contain duplicate triples.
Example:
Given array: S = [-1, 0, 1, 2,-1,-4],
Solution: [[-1, 0, 1],[-1,-1, 2]].
Just see the title of the topic, the first thought is the brute force solution, the array after sorting directly nested three loops, this is simple, but the complexity of the time is really n^3, when the data volume is too large to consume too much, when the submission did not pass.
After thinking for a while to think of some of the optimization scheme, but in essence there is no reduction of the secondary side, so still need to improve, the goal is n^2.
First, the target is n^2, you need to scan the array two times, the first loop is not a problem, but to reduce the second and third cycle to scan again, because it is to add two numbers equal to a value, so the ordered array from the back and back to the next scan, until the meeting, if you continue to loop after the meeting, The results will be repeated,
So you can jump out of the loop when you meet. This way, you only need to scan the array once to reach the two-layer loop result. The simple idea is this, in the implementation of the time to consider some other issues, the implementation of the code is as follows:
Public classSolution { PublicList<list<integer>> Threesum (int[] nums) {List<List<Integer>> result =NewLinkedlist<list<integer>>(); if(nums.length<3){ returnresult; } arrays.sort (Nums); intLeft=0,right=nums.length-1; for(intmid=0;mid< nums.length-2;mid++){ if(nums[mid]>0) Break; if(Mid = = 0 | | (Mid > 0 && nums[mid]! = nums[mid-1]) { left=mid+1; Right=nums.length-1; while(left<Right ) { if(Nums[left]+nums[mid]+nums[right] ==0) {Result.add (Arrays.aslist (nums[mid],nums[left],nums[right)); while(Left < right && nums[left] = = nums[left+1]) left++; while(Left < right && nums[right] = = Nums[right-1]) right--; Left++; Right--; }Else if(nums[left]+nums[mid]+nums[right]<0) { left++; }Else if(nums[left]+nums[mid]+nums[right]>0) { Right--; } } } } returnresult; }}
Algorithm title: Three numbers added equals a specific value