-
Notifications
You must be signed in to change notification settings - Fork 0
/
15.三数之和.js
42 lines (40 loc) · 1.01 KB
/
15.三数之和.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/*
* @lc app=leetcode.cn id=15 lang=javascript
*
* [15] 三数之和
*/
// @lc code=start
/**
* @param {number[]} nums
* @return {number[][]}
*/
var threeSum = function (nums) {
const len = nums.length;
let res = [];
if (len <= 2) return res;
const newList = nums.sort((a, b) => a - b);
for (let i = 0; i < len - 2; i++) {
if (i > 0 && nums[i] === nums[i - 1]) continue;
let l = i + 1;
let r = len - 1;
while (l < r) {
if (nums[i] + nums[l] + nums[r] > 0) {
r -= 1;
} else if (nums[i] + nums[l] + nums[r] < 0) {
l += 1;
} else {
res.push([nums[i], nums[l], nums[r]]);
while (l < r && nums[l] === nums[l + 1]) {
l += 1;
}
while (r > l && nums[r] === nums[r - 1]) {
r -= 1;
}
l += 1;
r -= 1;
}
}
}
return res;
};
// @lc code=end