Skip to content

Commit c633a35

Browse files
committed
Add solution #15
1 parent 74234c3 commit c633a35

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
12|[Integer to Roman](./0012-integer-to-roman.js)|Medium|
2121
13|[Roman to Integer](./0013-roman-to-integer.js)|Easy|
2222
14|[Longest Common Prefix](./0014-longest-common-prefix.js)|Easy|
23+
15|[3Sum](./0015-3sum.js)|Medium|
2324
17|[Letter Combinations of a Phone Number](./0017-letter-combinations-of-a-phone-number.js)|Medium|
2425
19|[Remove Nth Node From End of List](./0019-remove-nth-node-from-end-of-list.js)|Medium|
2526
20|[Valid Parentheses](./0020-valid-parentheses.js)|Easy|

solutions/0015-3sum.js

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/**
2+
* 15. 3Sum
3+
* https://leetcode.com/problems/3sum/
4+
* Difficulty: Medium
5+
*
6+
* Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j,
7+
* i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.
8+
*
9+
* Notice that the solution set must not contain duplicate triplets.
10+
*/
11+
12+
/**
13+
* @param {number[]} nums
14+
* @return {number[][]}
15+
*/
16+
var threeSum = function(nums) {
17+
const result = new Set();
18+
19+
nums.sort((a, b) => a - b);
20+
21+
for (let i = 0; i < nums.length - 2; i++) {
22+
let j = i + 1;
23+
let k = nums.length - 1;
24+
25+
while (j < k) {
26+
const sum = nums[i] + nums[j] + nums[k];
27+
if (!sum) {
28+
result.add(JSON.stringify([nums[i], nums[j++], nums[k--]]));
29+
} else if (sum > 0) {
30+
k--;
31+
} else {
32+
j++;
33+
}
34+
}
35+
}
36+
37+
return [...result].map(JSON.parse);
38+
};

0 commit comments

Comments
 (0)