3Sum
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)
https://leetcode.com/problems/3sum/
At first I thought of the violent triple loop, suggesting that double pointers.
To sort first, the solution of the problem depends on the order.
The outer loop loops from beginning to end, with double pointers to the inner layer.
Each round of the inner layer adds the value of the two pointers to the outer loop, if the equality is found, if it is less than 0, the head pointer goes backward, and the pointer is greater than 0. It is possible to do so based on an already sequenced order.
1 /**2 * @param {number[]} nums3 * @return {number[][]}4 */5 varThreesum =function(nums) {6 varres = [];7Nums =nums.sort (sorting);8 9 for(vari = 0; i < nums.length-2; i++){Ten if(Nums[i-1]!== undefined && nums[i-1] = = =Nums[i]) { One Continue; A } - varCurr =Nums[i]; - varm = i + 1; the varn = nums.length-1; - while(M <N) { - if(Nums[m] + nums[n] + Curr = = 0){ - Res.push ([Curr, Nums[m], Nums[n]]); + while(M < n && nums[m] = = = Nums[m + 1]){ -m++; + } A while(M < n && nums[n] = = = Nums[n-1]){ atn--; - } -m++; n--; -}Else if(Nums[m] + nums[n] + Curr > 0){ -n--; -}Else { inm++; - } to } + } - returnRes; the * functionsorting (A, b) { $ if(A >b) {Panax Notoginseng return1; -}Else if(A <b) { the return-1; +}Else{ A return0; the } + } -};
[Leetcode] [Javascript]3sum