Skip to content

Commit 79d20f3

Browse files
committed
Add solution #18
1 parent 0222bef commit 79d20f3

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
15|[3Sum](./0015-3sum.js)|Medium|
2424
16|[3Sum Closest](./0016-3sum-closest.js)|Medium|
2525
17|[Letter Combinations of a Phone Number](./0017-letter-combinations-of-a-phone-number.js)|Medium|
26+
18|[4Sum](./0018-4sum.js)|Medium|
2627
19|[Remove Nth Node From End of List](./0019-remove-nth-node-from-end-of-list.js)|Medium|
2728
20|[Valid Parentheses](./0020-valid-parentheses.js)|Easy|
2829
21|[Merge Two Sorted Lists](./0021-merge-two-sorted-lists.js)|Easy|

solutions/0018-4sum.js

+59
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
/**
2+
* 18. 4Sum
3+
* https://leetcode.com/problems/4sum/
4+
* Difficulty: Medium
5+
*
6+
* Given an array nums of n integers, return an array of all the unique
7+
* quadruplets [nums[a], nums[b], nums[c], nums[d]] such that:
8+
* - 0 <= a, b, c, d < n
9+
* - a, b, c, and d are distinct.
10+
* - nums[a] + nums[b] + nums[c] + nums[d] == target
11+
*
12+
* You may return the answer in any order.
13+
*/
14+
15+
/**
16+
* @param {number[]} nums
17+
* @param {number} target
18+
* @return {number[][]}
19+
*/
20+
var fourSum = function(nums, target) {
21+
const result = [];
22+
23+
nums.sort((a, b) => a - b);
24+
25+
for (let i = 0; i < nums.length - 3; i++) {
26+
for (let j = i + 1; j < nums.length - 2; j++) {
27+
let high = nums.length - 1;
28+
let low = j + 1;
29+
30+
while (low < high) {
31+
const sum = nums[i] + nums[j] + nums[low] + nums[high];
32+
33+
if (sum === target) {
34+
result.push([nums[i], nums[j], nums[low], nums[high]]);
35+
while (nums[low] === nums[low + 1]) {
36+
low++;
37+
}
38+
while (nums[high] === nums[high - 1]) {
39+
high--;
40+
}
41+
low++;
42+
high--;
43+
} else if (sum < target) {
44+
low++;
45+
} else {
46+
high--;
47+
}
48+
}
49+
while (nums[j] === nums[j + 1]) {
50+
j++;
51+
}
52+
}
53+
while (nums[i] === nums[i + 1]) {
54+
i++;
55+
}
56+
}
57+
58+
return result;
59+
};

0 commit comments

Comments
 (0)