From 2ea72e3e4345e0de2feed93b4a74dd9bbbc25b68 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Fri, 14 Jan 2022 21:59:34 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880015.=E4=B8=89?= =?UTF-8?q?=E6=95=B0=E4=B9=8B=E5=92=8C.md=EF=BC=89=EF=BC=9A=E5=A2=9E?= =?UTF-8?q?=E5=8A=A0typescript=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0015.三数之和.md | 36 +++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/problems/0015.三数之和.md b/problems/0015.三数之和.md index c78ab06d..8992c5f4 100644 --- a/problems/0015.三数之和.md +++ b/problems/0015.三数之和.md @@ -332,7 +332,43 @@ var threeSum = function(nums) { return res; }; ``` +TypeScript: +```typescript +function threeSum(nums: number[]): number[][] { + nums.sort((a, b) => a - b); + let length = nums.length; + let left: number = 0, + right: number = length - 1; + let resArr: number[][] = []; + for (let i = 0; i < length; i++) { + if (i > 0 && nums[i] === nums[i - 1]) { + continue; + } + left = i + 1; + right = length - 1; + while (left < right) { + let total: number = nums[i] + nums[left] + nums[right]; + if (total === 0) { + resArr.push([nums[i], nums[left], nums[right]]); + left++; + right--; + while (nums[right] === nums[right + 1]) { + right--; + } + while (nums[left] === nums[left - 1]) { + left++; + } + } else if (total < 0) { + left++; + } else { + right--; + } + } + } + return resArr; +}; +``` ruby: ```ruby