Skip to content

Commit 437c246

Browse files
committed
leetcode: add question 15
1 parent 512785b commit 437c246

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

15.data

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
[-1, 0, 1, 2, -1, -4]
2+
[0,0,0,0]
3+
[-2,0,1,1,2]
4+
[-2,0,0,2,2]

15.三数之和.js

+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/*
2+
* @lc app=leetcode.cn id=15 lang=javascript
3+
*
4+
* [15] 三数之和
5+
*
6+
* 1. 先排序
7+
* 2. 选取标杆元素, 左右推进向中间查找. 标杆元素从最左面选取, 后面遇到相同标杆值可以直接跳过
8+
* 3. 向中间推进时, 需要跳过相同值
9+
*
10+
*/
11+
12+
// @lc code=start
13+
/**
14+
* @param {number[]} nums
15+
* @return {number[][]}
16+
*/
17+
var threeSum = function(nums) {
18+
nums.sort((a, b) => a - b);
19+
20+
const result = [];
21+
for (let i = 0; i < nums.length - 2; i++) {
22+
if (nums[i] === nums[i - 1]) {
23+
continue;
24+
}
25+
26+
let a = i + 1;
27+
let b = nums.length - 1;
28+
while (a < b) {
29+
const sum = nums[i] + nums[a] + nums[b];
30+
if (sum === 0) {
31+
result.push([nums[i], nums[a], nums[b]]);
32+
}
33+
if (sum <= 0) {
34+
do {
35+
a++;
36+
} while (nums[a] === nums[a - 1]);
37+
}
38+
if (sum >= 0) {
39+
do {
40+
b--;
41+
} while (nums[b] === nums[b + 1]);
42+
}
43+
}
44+
}
45+
46+
return result;
47+
};
48+
// @lc code=end
49+

0 commit comments

Comments
 (0)