Skip to content

Commit 3b32de0

Browse files
author
์ดํ˜ธ์ฐฌ
committed
3sum solution
1 parent 4b1490f commit 3b32de0

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

โ€Ž3sum/lhc0506.js

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {number[][]}
4+
*/
5+
var threeSum = function(nums) {
6+
const result = [];
7+
const numsMap = {};
8+
9+
nums.forEach((num, index) => {
10+
numsMap[num] = (numsMap[num] || 0) + 1;
11+
12+
});
13+
14+
for (let i = 0; i < nums.length - 1; i++) {
15+
for (let j = i + 1; j < nums.length; j++) {
16+
const a = nums[i];
17+
const b = nums[j];
18+
const targetNum = -(a + b);
19+
20+
if (!numsMap[targetNum]) {
21+
continue;
22+
}
23+
24+
if ((targetNum === a || targetNum === b) && numsMap[targetNum] === 1) {
25+
continue;
26+
}
27+
28+
if (targetNum === a && targetNum === b && numsMap[targetNum] <= 2) {
29+
continue;
30+
}
31+
32+
const triplet = [a, b, targetNum].sort((x, y) => x - y);
33+
const key = triplet.join(',');
34+
35+
if (seen.has(key)) {
36+
continue;
37+
}
38+
39+
seen.add(key);
40+
41+
result.push(triplet);
42+
}
43+
}
44+
45+
return result;
46+
};
47+
48+
49+
//์‹œ๊ฐ„ ๋ณต์žก๋„ O(nยฒ) , ๊ณต๊ฐ„ ๋ณต์žก๋„ O(nยฒ) ๋ผ๊ณ  ์ƒ๊ฐํ–ˆ๋Š”๋ฐ Time Limit Exceeded ์—๋Ÿฌ ๋ฐœ์ƒ
50+
// ์ถ”ํ›„ ๋‹ค์‹œ ํ’€์–ด๋ณผ ์˜ˆ์ •

0 commit comments

Comments
ย (0)