-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path15.3-sum.js
54 lines (49 loc) · 1.02 KB
/
15.3-sum.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
/*
* @lc app=leetcode id=15 lang=javascript
*
* [15] 3Sum
*/
/**
* @param {number[]} nums
* @return {number[][]}
*/
var threeSum = function (nums) {
// 如果存在 0 的情况
var arr = nums.sort((x, y) => x - y)
let left = 0
let right = arr.length > 0 ? arr.length - 1 : 0
let newarr = []
while (left < right) {
const remain = arr[left] + arr[right]
const indexes = arr.map((item, index) => {
if (item === -remain) {
return index
}
}).filter(item => !isNaN(item))
// 无0
if (indexes.length > 0 &&
indexes.some(index =>
index !== left &&
index !== right
)
) {
if (arr[right] > -remain && arr[left] !== arr[left - 1]) {
newarr.push(
[arr[left], arr[right], -remain]
)
} else if(arr[right] === arr[left]) {
if (newarr.length === 0) {
newarr.push(
[0,0,0]
)
}
}
}
if (remain < 0) {
left++
} else {
right--
}
}
return newarr
};