-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path15.三数之和.js
46 lines (40 loc) · 897 Bytes
/
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
43
44
45
46
/*
* @lc app=leetcode.cn id=15 lang=javascript
*
* [15] 三数之和
*/
// @lc code=start
/**
* @param {number[]} nums
* @return {number[][]}
*/
var threeSum = function (nums) {
nums.sort((a, b) => a - b);
const result = [];
if (nums.length < 3) return [];
for (let i = 0, len = nums.length; i < len; i++) {
if (nums[i] > 0) return result;
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) {
result.push([nums[i], nums[L], nums[R]])
while (L < R && nums[L] === nums[L + 1]) {
L++;
}
while(L < R && nums[R] === nums[R - 1]) {
R--;
}
L++;
R--;
} else if (nums[i] + nums[L] + nums[R] > 0) {
R--;
} else {
L++;
}
}
}
return result;
};
// @lc code=end