forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgwbaik9717.js
More file actions
38 lines (31 loc) · 854 Bytes
/
gwbaik9717.js
File metadata and controls
38 lines (31 loc) · 854 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// Time complexity: O(n^2)
// Space complexity: O(n)
/**
* @param {number[]} nums
* @return {number[][]}
*/
var threeSum = function (nums) {
const sumsDict = new Set();
const sortedNums = nums.toSorted((a, b) => a - b);
const n = nums.length;
for (let i = 0; i < n - 2; i++) {
let left = i + 1;
let right = n - 1;
const fixed = sortedNums[i];
const targetSum = 0 - fixed;
while (left < right) {
const currentSum = sortedNums[left] + sortedNums[right];
if (currentSum < targetSum) {
left++;
} else if (currentSum > targetSum) {
right--;
} else {
const key = [fixed, sortedNums[left], sortedNums[right]];
sumsDict.add(key.join(","));
left++;
right--;
}
}
}
return Array.from(sumsDict).map((nums) => nums.split(",").map(Number));
};