Skip to content

Commit 37fbb8c

Browse files
committed
add: 3sum solution
1 parent 3bcf5bc commit 37fbb8c

1 file changed

Lines changed: 45 additions & 0 deletions

File tree

โ€Ž3sum/Cyjin-jani.jsโ€Ž

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
// ! ํ’€๋‹ค๊ฐ€ ๋ง‰ํ˜€์„œ AI์˜ ๋„์›€(ํžŒํŠธ)์„ ๋ฐ›์•„ ์™„์„ฑํ•œ ์ฝ”๋“œ์ž…๋‹ˆ๋‹ค..
2+
3+
// tc: o(n^2)
4+
// sc: o(n)
5+
const threeSum = function (nums) {
6+
const answer = [];
7+
8+
// ๋จผ์ € ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌํ•˜๊ธฐ
9+
const sortedArr = nums.sort((a, b) => a - b);
10+
11+
for (let i = 0; i < sortedArr.length; i++) {
12+
if (i > 0 && sortedArr[i] === sortedArr[i - 1]) continue;
13+
14+
let left = i + 1;
15+
let right = sortedArr.length - 1;
16+
17+
while (left < right) {
18+
const sum = sortedArr[i] + sortedArr[left] + sortedArr[right];
19+
20+
if (sum === 0) {
21+
answer.push([sortedArr[i], sortedArr[left], sortedArr[right]]);
22+
23+
// ์ค‘๋ณต ์ฒ˜๋ฆฌ
24+
// left๊ฐ€ ๊ฐ€๋ฆฌํ‚ค๋Š” ์ˆซ์ž๊ฐ€ ์ด์ „ ์ˆซ์ž์™€ ๋˜‘๊ฐ™๋‹ค๋ฉด ๊ณ„์† ํŒจ์Šค
25+
while (left < right && sortedArr[left] === sortedArr[left + 1]) {
26+
left++;
27+
}
28+
// right๊ฐ€ ๊ฐ€๋ฆฌํ‚ค๋Š” ์ˆซ์ž๊ฐ€ ์ด์ „ ์ˆซ์ž์™€ ๋˜‘๊ฐ™๋‹ค๋ฉด ๊ณ„์† ํŒจ์Šค
29+
while (left < right && sortedArr[right] === sortedArr[right - 1]) {
30+
right--;
31+
}
32+
// ๋˜‘๊ฐ™์€ ์ˆซ์ž๋“ค์„ ๋‹ค ๊ฑด๋„ˆ๋›ฐ์—ˆ์œผ๋‹ˆ, ์ƒˆ๋กœ์šด ์ˆซ์ž๋กœ ๋„˜์–ด๊ฐ
33+
left++;
34+
right--;
35+
} else if (sum < 0) {
36+
// 0๋ณด๋‹ค ์ž‘์œผ๋ฉด left๋ฅผ ํ‚ค์›€ (์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌ์ด๊ธฐ ๋•Œ๋ฌธ)
37+
left++;
38+
} else {
39+
right--;
40+
}
41+
}
42+
}
43+
44+
return answer;
45+
};

0 commit comments

Comments
ย (0)