From fb6131a64e096fc2207bd4ac9cd8cc2fbbf092cb Mon Sep 17 00:00:00 2001 From: yi-ge Date: Fri, 12 Jun 2020 13:12:29 +0800 Subject: [PATCH] =?UTF-8?q?add:=20=E4=B8=89=E6=95=B0=E4=B9=8B=E5=92=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 5 +++++ src/math/3sum.js | 31 +++++++++++++++++++++++++++++++ test/math/3sum.test.js | 8 ++++++++ 3 files changed, 44 insertions(+) create mode 100644 src/math/3sum.js create mode 100644 test/math/3sum.test.js diff --git a/README.md b/README.md index 75531d6..b183a22 100644 --- a/README.md +++ b/README.md @@ -443,6 +443,11 @@ LeetCode 与 LintCode 解题记录。此为个人练习仓库,代码中对重 - LeetCode 4. 寻找两个正序数组的中位数 - LintCode 65. 两个排序数组的中位数 +- [三数之和](src/math/3sum.js) + + - LeetCode 15. 三数之和 + - LintCode 57. 三数之和 + ## 堆 - [超级丑数](src/stack/super-ugly-number.js)【未完成】 diff --git a/src/math/3sum.js b/src/math/3sum.js new file mode 100644 index 0000000..183ae34 --- /dev/null +++ b/src/math/3sum.js @@ -0,0 +1,31 @@ +// 一年前做过。复制自:https://leetcode-cn.com/problems/3sum/solution/three-sum-ti-jie-by-wonderful611/ +/** + * @param {number[]} nums + * @return {number[][]} + */ +export const threeSum = function (nums) { + const res = [] + const length = nums.length + nums.sort((a, b) => a - b) // 先排个队,最左边是最弱(小)的,最右边是最强(大)的 + if (nums[0] <= 0 && nums[length - 1] >= 0) { // 优化1: 整个数组同符号,则无解 + for (let i = 0; i < length - 2;) { + if (nums[i] > 0) break // 优化2: 最左值为正数则一定无解 + let first = i + 1 + let last = length - 1 + do { + if (first >= last || nums[i] * nums[last] > 0) break // 两人选相遇,或者三人同符号,则退出 + const result = nums[i] + nums[first] + nums[last] + if (result === 0) { // 如果可以组队 + res.push([nums[i], nums[first], nums[last]]) + } + if (result <= 0) { // 实力太弱,把菜鸟那边右移一位 + while (first < last && nums[first] === nums[++first]) { } // 如果相等就跳过 + } else { // 实力太强,把大神那边右移一位 + while (first < last && nums[last] === nums[--last]) { } + } + } while (first < last) + while (nums[i] === nums[++i]) { } + } + } + return res +} diff --git a/test/math/3sum.test.js b/test/math/3sum.test.js new file mode 100644 index 0000000..5ac058c --- /dev/null +++ b/test/math/3sum.test.js @@ -0,0 +1,8 @@ +import { threeSum } from '../../src/math/3sum.js' + +test('三数之和', () => { + expect(threeSum([-1, 0, 1, 2, -1, -4])).toEqual([ + [-1, -1, 2], + [-1, 0, 1] + ]) +})