-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
63 lines (48 loc) · 1.18 KB
/
index.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
59
60
61
62
63
/**
* @param {number[]} nums
* @param {number} target
* @return {number[][]}
*/
var fourSum = function(nums, target) {
nums.sort(function(a, b) {
return a - b;
});
var hash = [];
var len = nums.length;
for (var i = 0; i < len; i++)
for (var j = i + 1; j < len; j++) {
var a = nums[i]
, b = nums[j]
, c = a + b;
if (hash[c] === undefined)
hash[c] = [[i, j]];
else
hash[c].push([i, j]);
}
var ans = [];
var hashSet = {};
for (var i = 0; i < len; i++)
for (var j = i + 1; j < len; j++) {
var a = nums[i]
, b = nums[j]
, sum = target - a - b;
if (!hash[sum])
continue;
for (var k = 0, _len = hash[sum].length; k < _len; k++) {
var item = hash[sum][k];
if (item[0] === i || item[1] === i || item[0] === j || item[1] === j)
continue;
var c = nums[item[0]]
, d = nums[item[1]];
var tmp = [a, b, c, d].sort(function(a, b) {
return a - b;
});
var str = tmp.join(',');
if (!hashSet[str]) {
hashSet[str] = true;
ans.push(tmp);
}
}
}
return ans;
};