
๋ฌธ์ ํด๊ฒฐ ๊ณผ์
โ๏ธ ๋๋ง์ ๋ฐฉ์์ผ๋ก ๋ฌธ์ ์ ๋ฆฌํ๊ธฐ (=์ฒด๊ณํ)
https://leetcode.com/problems/linked-list-cycle/?envType=study-plan-v2&envId=top-interview-150
Linked List Cycle - LeetCode
Can you solve this real interview question? Linked List Cycle - Given head, the head of a linked list, determine if the linked list has a cycle in it. There is a cycle in a linked list if there is some node in the list that can be reached again by continuo
leetcode.com
์ฃผ์ด์ง ์ฐ๊ฒฐ ๋ฆฌ์คํธ์ ์ฌ์ดํด์ด ์๋ค๋ฉด true, ์๋ค๋ฉด false๋ฅผ ๋ฐํํ๋ผ
- ์
๋ ฅ
- nodes | ListNode := ๋ ธ๋๋ค, | nodes | ∈ [0, 10^4]
- Node.val | int := ๋ ธ๋์ ๊ฐ, | Node.val | ∈ [-10^5, 10^5]
- ์ถ๋ ฅ
- hasCycle | boolean := ์ฌ์ดํด์ ๊ฐ์ง๊ณ ์๋์ง
- ์กฐ๊ฑด
- pos๋ ์ ํจํ ์ธ๋ฑ์ค ํน์ -1์ด๋ค.
- pos๋ ์ฌ์ดํด์ ์์์ ์ด๋ค.
- pos๊ฐ -1์ด๋ผ๋ฉด ์ฌ์ดํด์ด ์๋ ๊ฒ์ด๋ค.
- pos๋ ์ ํจํ ์ธ๋ฑ์ค ํน์ -1์ด๋ค.
๐ ์ด๋ค ์์ผ๋ก ์ ๊ทผํ๋๊ฐ?
๋งํฌ๋ ๋ฆฌ์คํธ์ ๊ฐ๋ ์ ์๊ณ ์์์ง๋ง, ์๊ณ ๋ฆฌ์ฆ ๋ฌธ์ ๋ ์ฒ์ ํ์ด๋ณด์๊ธฐ ๋๋ฌธ์ ์ด๋ป๊ฒ ์ ๊ทผํด์ผํ ์ง ์ ํ ๊ฐ์ด ์กํ์ง ์์๋ค.
์ฒซ ๋ฌธ์ ๋ ํ์ด๋ฅผ ํ์ธํ๊ณ ์ดํ๋ถํฐ ํผ์ ํ์ด๋ณด๊ธฐ๋ก ํ๋ค.
๋ค๋ฅธ ์ฌ๋์ ์ฝ๋๋ฅผ ํ๊ตฌํด๋ณด๊ธฐ
๐ฏ ๊ตฌํ ์ฝ๋
ํ๋ก์ด๋์ ํ ๋ผ์ ๊ฑฐ๋ถ์ด(Floyd's Tortoise and Hare) ์๊ณ ๋ฆฌ์ฆ
ํ ์นธ์ฉ ์ด๋ํ๋ slow ํฌ์ธํฐ์ ๋ ์นธ์ฉ ์ด๋ํ๋ fast ํฌ์ธํฐ, ๋ ๊ฐ์ ํฌ์ธํฐ๋ฅผ ์ด์ฉํด ์ฌ์ดํด์ ์ฐพ๋๋ค. (์ฌ์ดํด์ด ์๋ค๋ฉด ๋ ํฌ์ธํฐ๋ ์ฌ์ดํด ์์์ ์ธ์ ๊ฐ๋ ๋ง๋๋ค.)
- head๋ถํฐ slow, fast ํฌ์ธํฐ๋ฅผ ๊ฐ๊ฐ ํ ์นธ, ๋ ์นธ์ฉ ์ด๋์ํจ๋ค.
- 1๋ฒ์ ๋ฐ๋ณตํ๋ค๊ฐ, slow์ fast์ ํฌ์ธํฐ๊ฐ ๊ฐ์์ง๋ค๋ฉด, ์ฌ์ดํด์ด ์กด์ฌํ๋ ๊ฒ์ด๋ค.
- ๋ง์ฝ slow ํน์ fast๊ฐ null์ ๋์ฐฉํ๋ค๋ฉด, ์ฌ์ดํด์ด ์กด์ฌํ์ง ์๋ ๊ฒ์ด๋ค.
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
if head == None: return False
slow, fast = head, head.next
while slow != fast:
if fast == None or fast.next == None: return False
slow = slow.next # ํ ์นธ ์ด๋
fast = fast.next.next # ๋ ์นธ ์ด๋
return True
โฑ ์ฑ๋ฅ ์ธก์ (์๊ฐ๋ณต์ก๋/๊ณต๊ฐ๋ณต์ก๋)
linear search์ด๊ธฐ ๋๋ฌธ์ ์๊ฐ ๋ณต์ก๋๋ O(N)์ด๋ค.
๋ํ ํฌ์ธํฐ(slow, fast) ๋ ๊ฐ๋ง ์ฌ์ฉ๋๊ธฐ ๋๋ฌธ์ ๊ณต๊ฐ ๋ณต์ก๋๋ O(1)์ด๋ค.
๋๋ ์
์๊ณ ๋ฆฌ์ฆ ๋ฌธ์ ๋ ์ข ์ข ํ์์ง๋ง ๋งํฌ๋ ๋ฆฌ์คํธ ๋ฌธ์ ๋ ์ฒ์์ด๋ผ ๋งค๊ฐ๋ณ์๋ก head: Optional[ListNode]๋ก ์ฃผ์ด์ง๋ ๊ฒ์ด ๋ฏ์ค์๋ค.
ํ ๋ผ์ ๊ฑฐ๋ถ์ด ์๊ณ ๋ฆฌ์ฆ๋ ์ฒ์ ํ์ตํ ๋ด์ฉ์ด์๋๋ฐ, ์ฌ์ดํด์ ์ ๋ฌด๋ฅผ ํ๋จํ ๋ slow์ fast ํฌ์ธํฐ๋ฅผ ์ฌ์ฉํ๋ ๊ฒ๋ ์์๋์ด์ผ๊ฒ ๋ค!
์ฐธ๊ณ ์๋ฃ
Leetcode 141. Linked List Cycle with Python
LeetCode ์ฐ๊ฒฐ ๋ชฉ๋ก ์ฃผ๊ธฐ ์๋ฃจ์ ์ค๋ช - Java
๋งํฌ๋ ๋ฆฌ์คํธ์ ์ฌ์ดํด ์ฐพ๊ธฐ (ํ๋ก์ด๋์ ํ ๋ผ์ ๊ฑฐ๋ถ์ด ์๊ณ ๋ฆฌ์ฆ)