-
Notifications
You must be signed in to change notification settings - Fork 0
/
#15_3Sum.js
49 lines (39 loc) · 1.02 KB
/
#15_3Sum.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
/**
* @param {number[]} nums
* @return {number[][]}
*/
var threeSum = function(nums) {
var map = new Map()
for (let i=0; i < nums.length; i++) {
var num = nums[i]
var target = 0 - num
var twoSums = findTwoSums(target, nums.slice(i+1))
twoSums.forEach(function(i) {
i.push(num)
i = i.sort()
map.set(i.toString(), 1)
})
}
var result = []
Array.from(map.keys()).forEach(function(i) {
var arr = i.split(",")
arr.map(k=> parseInt(k))
result.push(arr)
})
return result
};
function findTwoSums(target, arr) {
var map = new Map()
var result = []
for (let i =0; i < arr.length; i++) {
var element = arr[i]
var targetElement = target - element
if (map.get(targetElement)) {
result.push([element, targetElement])
}
if (!map.get(element)) {
map.set(element, 1)
}
}
return result
}