forked from sl1673495/leetcode-javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
三数之和.js
41 lines (38 loc) · 932 Bytes
/
三数之和.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
/**
* @param {number[]} nums
* @return {number[][]}
*/
let twoSum = function(nums, target) {
let map = new Map()
let results = []
for (let i = 0; i < nums.length; i++) {
let num = nums[i]
let result = map.get(target - num)
if (result !== undefined) {
results.push([nums[result], num])
}
map.set(num, i)
}
return results
}
let threeSum = function(nums) {
nums.sort((a, b) => a - b)
let set = new Set()
let results = []
for (let i = 0; i < nums.length - 2; i++) {
let find = twoSum(nums.slice(i + 1), -nums[i])
if (find) {
find.forEach((arr) => {
if (!set.has(arr.join(''))) {
results.push([nums[i], ...arr])
}
set.add(arr.join(''))
})
}
}
return results
}
console.log(threeSum([-1,0,1,2,-1,-4]))
/**
* 利用两数之和的变形来求解,循环判断第三个数的负数是否能和另外两个数相加得到。
*/