From d5f21d534198069fee0dd4a90397d1322d435179 Mon Sep 17 00:00:00 2001 From: eat to 160 pounds <2915390277@qq.com> Date: Sun, 24 Apr 2022 21:05:31 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E4=BA=86=E4=B8=89=E6=95=B0?= =?UTF-8?q?=E4=B9=8B=E5=92=8Cjavascript=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0015.三数之和.md | 70 +++++++++++++---------------------- 1 file changed, 26 insertions(+), 44 deletions(-) diff --git a/problems/0015.三数之和.md b/problems/0015.三数之和.md index bfde6b35..cc184c87 100644 --- a/problems/0015.三数之和.md +++ b/problems/0015.三数之和.md @@ -313,54 +313,36 @@ func threeSum(nums []int)[][]int{ javaScript: ```js -/** - * @param {number[]} nums - * @return {number[][]} - */ - -// 循环内不考虑去重 var threeSum = function(nums) { - const len = nums.length; - if(len < 3) return []; - nums.sort((a, b) => a - b); - const resSet = new Set(); - for(let i = 0; i < len - 2; i++) { - if(nums[i] > 0) break; - let l = i + 1, r = len - 1; + const res = [], len = nums.length + // 将数组排序 + nums.sort((a, b) => a - b) + for (let i = 0; i < len; i++) { + let l = i + 1, r = len - 1, iNum = nums[i] + // 数组排过序,如果第一个数大于0直接返回res + if (iNum > 0) return res + // 去重 + if (iNum == nums[i - 1]) continue while(l < r) { - const sum = nums[i] + nums[l] + nums[r]; - if(sum < 0) { l++; continue }; - if(sum > 0) { r--; continue }; - resSet.add(`${nums[i]},${nums[l]},${nums[r]}`); - l++; - r--; + let lNum = nums[l], rNum = nums[r], threeSum = iNum + lNum + rNum + // 三数之和小于0,则左指针向右移动 + if (threeSum < 0) l++ + else if (threeSum > 0) r-- + else { + res.push([iNum, lNum, rNum]) + // 去重 + while(l < r && nums[l] == nums[l + 1]){ + l++ + } + while(l < r && nums[r] == nums[r - 1]) { + r-- + } + l++ + r-- + } } } - return Array.from(resSet).map(i => i.split(",")); -}; - -// 去重优化 -var threeSum = function(nums) { - const len = nums.length; - if(len < 3) return []; - nums.sort((a, b) => a - b); - const res = []; - for(let i = 0; i < len - 2; i++) { - if(nums[i] > 0) break; - // a去重 - if(i > 0 && nums[i] === nums[i - 1]) continue; - let l = i + 1, r = len - 1; - while(l < r) { - const sum = nums[i] + nums[l] + nums[r]; - if(sum < 0) { l++; continue }; - if(sum > 0) { r--; continue }; - res.push([nums[i], nums[l], nums[r]]) - // b c 去重 - while(l < r && nums[l] === nums[++l]); - while(l < r && nums[r] === nums[--r]); - } - } - return res; + return res }; ``` TypeScript: