Skip to content

Commit 5d42bb8

Browse files
committed
Create 18.四数之和.js
1 parent f1ac02a commit 5d42bb8

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

18.四数之和.js

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
* @param {number[]} nums
3+
* @param {number} target
4+
* @return {number[][]}
5+
*/
6+
var fourSum = function(nums, target) {
7+
nums.sort((a, b) => a - b);
8+
9+
const result = [];
10+
for (let i = 0; i < nums.length - 3; i++) {
11+
if (i > 0 && nums[i] === nums[i - 1]) {
12+
continue;
13+
}
14+
15+
for (let j = i + 1; j < nums.length - 2; j++) {
16+
if (j > i + 1 && nums[j] === nums[j - 1]) {
17+
continue;
18+
}
19+
20+
let a = j + 1;
21+
let b = nums.length - 1;
22+
while (a < b) {
23+
const sum = nums[i] + nums[j] + nums[a] + nums[b];
24+
if (sum === target) {
25+
result.push([nums[i], nums[j], nums[a], nums[b]]);
26+
}
27+
if (sum <= target) {
28+
do {
29+
a++;
30+
} while (nums[a] === nums[a - 1]);
31+
}
32+
if (sum >= target) {
33+
do {
34+
b--;
35+
} while (nums[b] === nums[b + 1]);
36+
}
37+
}
38+
}
39+
}
40+
41+
return result;
42+
};
43+
44+
console.log(fourSum([-3,-1,0,2,4,5],
45+
2));

0 commit comments

Comments
 (0)