Skip to content

Commit d45bd00

Browse files
committed
add solution for leetcode 18
1 parent 22a0507 commit d45bd00

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -394,7 +394,7 @@ LeetCode
394394
|21|[Merge Two Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists/)| [java](./algorithm/mergeTwoSortedLists/Solution.java) |Easy|
395395
|20|[Valid Parentheses](https://leetcode.com/problems/valid-parentheses/)| |Easy|
396396
|19|[Remove Nth Node From End of List](https://leetcode.com/problems/remove-nth-node-from-end-of-list/)| [js](./algorithms/removeNthNodeFromEndOfList/removeNthNodeFromEndOfList.js) |Easy|
397-
|18|[4Sum](https://leetcode.com/problems/4sum/)| |Medium|
397+
|18|[4Sum](https://leetcode.com/problems/4sum/)| [js](./algorithms/4Sum/4Sum.js) |Medium|
398398
|17|[Letter Combinations of a Phone Number](https://leetcode.com/problems/letter-combinations-of-a-phone-number/)| |Medium|
399399
|16|[3Sum Closest](https://leetcode.com/problems/3sum-closest/)| |Medium|
400400
|15|[3Sum](https://leetcode.com/problems/3sum/)| [js](./algorithms/3Sum/3Sum.js) |Medium|

algorithms/4Sum/4Sum.js

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
var fourSum = function(nums, target) {
2+
const res = [];
3+
const len = nums.length;
4+
if (nums == null || len < 4) return res;
5+
6+
nums = nums.sort((a, b) => a - b);
7+
8+
for (let i = 0; i < len - 3; i++) {
9+
//计算当前的最小值,如果最小值都比target大,或者最大值都比target小不用再继续计算了
10+
if (nums[i] + nums[i + 1] + nums[i + 2] + nums[i + 3] > target ||
11+
nums[len - 1] + nums[len - 2] + nums[len - 3] + nums[len -4] < target) break;
12+
if (i === 0 || nums[i] !== nums[i-1]) {
13+
for (let j = i + 1; j < len - 2; j++) {
14+
if (j === i + 1 || nums[j] !== nums[j - 1]) {
15+
let R = len - 1, L = j + 1;
16+
//计算当前的最小值,如果最小值都比target大,不用再继续计算了
17+
if (nums[i] + nums[j] + nums[L] + nums[L + 1] > target) continue;
18+
//计算当前最大值,如果最大值都比target小,不用再继续计算了
19+
if (nums[i] + nums[j] + nums[R] + nums[R - 1] < target) continue;
20+
while (L < R) {
21+
let sum = nums[i] + nums[j] + nums[L] + nums[R];
22+
if (sum == target) {
23+
res.push([nums[i], nums[j], nums[L], nums[R]]);
24+
}
25+
if (sum < target) {
26+
while (nums[L] === nums[++L]);
27+
} else {
28+
while (nums[R] === nums[--R]);
29+
}
30+
}
31+
}
32+
}
33+
}
34+
}
35+
return res;
36+
};

0 commit comments

Comments
 (0)