4Sum
Given an array S of n integers, is there elements a, b, C, and D in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.
Note:
- Elements in a quadruplet (a,b,c,D) must is in non-descending order. (ie, a ≤ b ≤ c ≤ d)
- The solution set must not contain duplicate quadruplets.
https://leetcode.com/problems/4sum/
I see tags have hashtable, think of the triple cycle is not used, there is no use of this solution.
First 22 merge, and then use the double pointer to find the result.
Although the AC, but wrote a lot of good sad, but also not fast, below the average level, this is not the same as agreed (╯‵-′) ╯︵┻━┻, it must be used in the wrong posture.
1 /**2 * @param {number[]} nums3 * @param {number} target4 * @return {number[][]}5 */6 varFoursum =function(nums, target) {7Nums =nums.sort (sorting);8 varresult = [];9 varCountappear = {}; Twosummap = {}, Twosumarr = [];Ten varIsfound =NewSet (); One varI, J, Twosum; A for(i = 0; i < nums.length; i++){ - if(!Countappear[nums[i]]) { -Countappear[nums[i]] = 1; the}Else{ -countappear[nums[i]]++; - } - for(j = i + 1; j < Nums.length; J + +){ +Twosum = Nums[i] +Nums[j]; - if(!Twosummap[twosum]) { + Twosumarr.push (twosum); ATwosummap[twosum] =[{small:nums[i], large:nums[j]}]; at}Else if(!Arrcontains (Twosummap[twosum], nums[i], nums[j])) { - Twosummap[twosum].push ({small:nums[i], large:nums[j]}); - } - } - } -Twosumarr =twosumarr.sort (sorting); in - varNumA, NumB, SUM4, TMP, join; to for(i = 0, j = twosumarr.length-1; I <=J;) { +NumA = Twosummap[twosumarr[i]], NumB =Twosummap[twosumarr[j]]; -SUM4 = Twosumarr[i] +Twosumarr[j]; the if(Sum4 = = =target) { * addcandidate (NumA, NumB, result); $ }Panax Notoginseng if(Sum4 <target) { -i++; the}Else{ +j--; A } the } + returnresult; - $ functionVerifyresult (arr) { $ varPrevious =NULL, Count = 0; - for(vari = 0; i < arr.length; i++){ - if(Arr[i]!==Previous) { thePrevious =Arr[i]; -Count = 1;Wuyi}Else{ thecount++; - if(Count >Countappear[previous]) { Wu return false; - } About } $ } - return true; - } - functionaddcandidate (NumA, NumB, result) { A varI, J; + for(i = 0; i < numa.length; i++){ the for(j = 0; J < Numb.length; J + +){ -TMP =[Numa[i].small, Numa[i].large, Numb[j].small, Numb[j].large]; $TMP =tmp.sort (sorting); the if(Verifyresult (tmp)) { theJoin = Tmp.join (' # '); the if(!Isfound.has (join)) { the Isfound.add (join); - Result.push (TMP); in } the } the } About } the } the functionarrcontains (arr, small, Large) { the for(vari = 0; i < arr.length; i++){ + if(Arr[i].small = = = Small && Arr[i].large = = =Large) { - return true; the }Bayi } the return false; the } - functionsorting (A, b) { - if(A >b) { the return1; the}Else if(A <b) { the return-1; the}Else{ - return0; the } the } the};
[Leetcode] [Javascript]4sum