-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathsolution1.js
58 lines (56 loc) · 999 Bytes
/
solution1.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
47
48
49
50
51
52
53
54
55
56
57
58
/**
* https://leetcode-cn.com/problems/3sum/
*
* 15. 三数之和
*
* Medium
*
* 不能有重复的组合
*
* 不采用 hashtable 的去重方案
*
* 260ms 95.96%
* 47.2mb 39.65%
*
*/
const threeSum = nums => {
let ans = []
nums.sort((a, b) => a - b)
// 特殊情况处理
if (nums[0] > 0) {
return ans
}
const max = nums.length
for (let x = 0; x < max - 2; x++) {
let y = x + 1
let z = max - 1
if (x > 0 && nums[x] === nums[x - 1]) {
// 去重
continue
}
while (y < z) {
const sum = nums[x] + nums[y] + nums[z]
if (sum === 0) {
ans.push([nums[x], nums[y], nums[z]])
y++
z--
// 去重
while (y < z && nums[y] === nums[y - 1]) {
y++
}
while (z > y && nums[z] === nums[z + 1]) {
z--
}
}
if (sum > 0) {
z--
continue
}
if (sum < 0) {
y++
continue
}
}
}
return ans
}