diff --git a/linked-list-cycle/moonjonghoo.js b/linked-list-cycle/moonjonghoo.js new file mode 100644 index 000000000..605663ec4 --- /dev/null +++ b/linked-list-cycle/moonjonghoo.js @@ -0,0 +1,47 @@ +// ## ๐Ÿ”— ๋ฌธ์ œ ๋งํฌ +// https://leetcode.com/problems/linked-list-cycle/ + +// ## โœจ ๋ฌธ์ œ ์š”์•ฝ +// ์—ฐ๊ฒฐ ๋ฆฌ์ŠคํŠธ์— ์‚ฌ์ดํด์ด ์žˆ๋Š”์ง€ ์—ฌ๋ถ€๋ฅผ ํŒ๋ณ„ํ•˜๋Š” ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค. + +// ## โœ… ํ’€์ด ๋ฐฉ๋ฒ• +// ### 1. HashSet ์‚ฌ์šฉ +// - ๋ฐฉ๋ฌธํ•œ ๋…ธ๋“œ๋ฅผ ์ €์žฅํ•˜๊ณ  ์ค‘๋ณต ๋ฐฉ๋ฌธ ์‹œ true +// - ์‹œ๊ฐ„๋ณต์žก๋„: O(n), ๊ณต๊ฐ„๋ณต์žก๋„: O(n) + +var hasCycle = function (head) { + let visited = new Set(); + let current = head; + + while (current !== null) { + if (visited.has(current)) { + return true; // ์ด๋ฏธ ๋ฐฉ๋ฌธํ•œ ๋…ธ๋“œ๋ฅผ ๋‹ค์‹œ ๋ฐฉ๋ฌธ => ์‚ฌ์ดํด ์กด์žฌ + } + visited.add(current); + current = current.next; + } + + return false; // ๋๊นŒ์ง€ ๊ฐ”๋‹ค๋ฉด ์‚ฌ์ดํด ์—†์Œ +}; + +// ### 2. Two Pointer ๋ฐฉ์‹ (Floyd's Algorithm) +// - slow, fast ํฌ์ธํ„ฐ ์ด์šฉ +// - ๋งŒ๋‚  ๊ฒฝ์šฐ โ†’ ์‚ฌ์ดํด ์กด์žฌ +// - ๋๊นŒ์ง€ ๋„๋‹ฌ โ†’ ์‚ฌ์ดํด ์—†์Œ +// - ์‹œ๊ฐ„๋ณต์žก๋„: O(n), ๊ณต๊ฐ„๋ณต์žก๋„: O(1) + +var hasCycle = function (head) { + let slow = head; + let fast = head; + + while (fast !== null && fast.next !== null) { + slow = slow.next; // ํ•œ ์นธ ์ด๋™ + fast = fast.next.next; // ๋‘ ์นธ ์ด๋™ + + if (slow === fast) { + return true; // ๋งŒ๋‚ฌ๋‹ค๋ฉด ์‚ฌ์ดํด ์กด์žฌ! + } + } + + return false; // ๋๊นŒ์ง€ ๊ฐ”๋‹ค๋ฉด ์‚ฌ์ดํด ์—†์Œ +};