add: 三数之和

This commit is contained in:
yi-ge 2020-06-12 13:12:29 +08:00
parent ada2de5c1a
commit fb6131a64e
3 changed files with 44 additions and 0 deletions

View File

@ -443,6 +443,11 @@ LeetCode 与 LintCode 解题记录。此为个人练习仓库,代码中对重
- LeetCode 4. 寻找两个正序数组的中位数 <https://leetcode-cn.com/problems/median-of-two-sorted-arrays/>
- LintCode 65. 两个排序数组的中位数 <https://www.lintcode.com/problem/median-of-two-sorted-arrays/description>
- [三数之和](src/math/3sum.js)
- LeetCode 15. 三数之和 <https://leetcode-cn.com/problems/3sum/>
- LintCode 57. 三数之和 <https://www.lintcode.com/problem/3sum/description>
## 堆
- [超级丑数](src/stack/super-ugly-number.js)【未完成】

31
src/math/3sum.js Normal file
View File

@ -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
}

8
test/math/3sum.test.js Normal file
View File

@ -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]
])
})