From 957a284c60ef4c34241982df5f76dacf61134d74 Mon Sep 17 00:00:00 2001 From: "qingyi.liu" Date: Sat, 22 May 2021 23:37:30 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E7=AC=AC18=E9=A2=98.=20?= =?UTF-8?q?=E5=9B=9B=E6=95=B0=E4=B9=8B=E5=92=8CjavaScript=E7=89=88?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0018.四数之和.md | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/problems/0018.四数之和.md b/problems/0018.四数之和.md index ff441bf7..067386bb 100644 --- a/problems/0018.四数之和.md +++ b/problems/0018.四数之和.md @@ -169,7 +169,39 @@ Python: Go: +javaScript: +```js +/** + * @param {number[]} nums + * @param {number} target + * @return {number[][]} + */ +var fourSum = function(nums, target) { + const len = nums.length; + if(len < 4) return []; + nums.sort((a, b) => a - b); + const res = []; + for(let i = 0; i < len - 3; i++) { + // 去重i + if(i > 0 && nums[i] === nums[i - 1]) continue; + for(let j = i + 1; j < len - 2; j++) { + // 去重j + if(j > i + 1 && nums[j] === nums[j - 1]) continue; + let l = j + 1, r = len - 1; + while(l < r) { + const sum = nums[i] + nums[j] + nums[l] + nums[r]; + if(sum < target) { l++; continue} + if(sum > target) { r--; continue} + res.push([nums[i], nums[j], nums[l], nums[r]]); + while(l < r && nums[l] === nums[++l]); + while(l < r && nums[r] === nums[--r]); + } + } + } + return res; +}; +``` -----------------------