Skip to content

Commit c6c3822

Browse files
committed
3sum solution
1 parent d72903d commit c6c3822

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

โ€Ž3sum/limlimjo.js

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {number[][]}
4+
*/
5+
var threeSum = function (nums) {
6+
const result = []; // ๊ฒฐ๊ณผ๊ฐ’
7+
nums.sort((a, b) => a - b); // ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ณ
8+
9+
// ๋ฐฐ์—ด ์ˆœ์ฐจ ํƒ์ƒ‰
10+
for (let i = 0; i < nums.length - 2; i++) {
11+
// ์ค‘๋ณต ๊ฐ’ ๊ฑด๋„ˆ๋œ€
12+
if (i > 0 && nums[i] === nums[i - 1]) continue;
13+
14+
let low = i + 1,
15+
high = nums.length - 1;
16+
17+
// low์™€ high ํฌ์ธํ„ฐ ์ด์šฉํ•ด ํ•ฉ์ด 0์ธ ๊ฐ’ ์ฐพ๊ธฐ
18+
while (low < high) {
19+
const sum = nums[i] + nums[low] + nums[high];
20+
if (sum < 0) low++;
21+
else if (sum > 0) high--;
22+
else {
23+
result.push([nums[i], nums[low], nums[high]]);
24+
// ์ค‘๋ณต๋œ ๊ฐ’ ๊ฑด๋„ˆ๋›ฐ๊ธฐ
25+
while (low < high && nums[low] === nums[low + 1]) low++;
26+
while (low < high && nums[high] === nums[high - 1]) high--;
27+
low++;
28+
high--;
29+
}
30+
}
31+
}
32+
33+
return result;
34+
};
35+
36+
// 1์‹œ๊ฐ„ ์ •๋„ ๋ฌธ์ œ ํ’€์ด๋ฅผ ํ•˜๋‹ค๊ฐ€ ์ •๋ ฌ๊นŒ์ง€ ํ•œ ๋‹ค์Œ ๊ทธ ์ดํ›„ ์–ด๋–ป๊ฒŒ ํ•ด์•ผํ• ์ง€ ๋ชฐ๋ผ ํ’€์ด ์ฐธ๊ณ 
37+
// ๋ฌธ์ œ ํ’€์ด์—์„œ ํ•ต์‹ฌ์€ ์ •๋ ฌ์„ ํ•œ ๋‹ค์Œ ๋‘ ๊ฐœ์˜ ํฌ์ธํ„ฐ๋ฅผ ์ง€์ •ํ•ด sum์ด 0์ธ ๊ฐ’์„ ์ฐพ๋Š” ๊ฒƒ
38+
// ์‹œ๊ฐ„ ๋ณต์žก๋„: O(n^2) ๋ฐฐ์—ด ์ˆœ์ฐจ ํƒ์ƒ‰
39+
// ๊ณต๊ฐ„ ๋ณต์žก๋„: O(1) ๊ฒฐ๊ณผ๊ฐ’ result

0 commit comments

Comments
ย (0)