Skip to content

Commit ddc84aa

Browse files
committed
feat: 15. 3Sum
1 parent 1eb02cb commit ddc84aa

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

3sum/gwbaik9717.js

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
// Time complexity: O(n^2)
2+
// Space complexity: O(n)
3+
4+
/**
5+
* @param {number[]} nums
6+
* @return {number[][]}
7+
*/
8+
var threeSum = function (nums) {
9+
const sumsDict = new Set();
10+
const sortedNums = nums.toSorted((a, b) => a - b);
11+
12+
const n = nums.length;
13+
14+
for (let i = 0; i < n - 2; i++) {
15+
let left = i + 1;
16+
let right = n - 1;
17+
const fixed = sortedNums[i];
18+
19+
const targetSum = 0 - fixed;
20+
21+
while (left < right) {
22+
const currentSum = sortedNums[left] + sortedNums[right];
23+
24+
if (currentSum < targetSum) {
25+
left++;
26+
} else if (currentSum > targetSum) {
27+
right--;
28+
} else {
29+
const key = [fixed, sortedNums[left], sortedNums[right]];
30+
sumsDict.add(key.join(","));
31+
left++;
32+
right--;
33+
}
34+
}
35+
}
36+
37+
return Array.from(sumsDict).map((nums) => nums.split(",").map(Number));
38+
};

0 commit comments

Comments
 (0)