File tree Expand file tree Collapse file tree 1 file changed +55
-0
lines changed Expand file tree Collapse file tree 1 file changed +55
-0
lines changed Original file line number Diff line number Diff line change 1+ # https://leetcode.com/problems/linked-list-cycle/
2+
3+ from typing import Optional
4+
5+ # Definition for singly-linked list.
6+ class ListNode :
7+ def __init__ (self , x ):
8+ self .val = x
9+ self .next = None
10+
11+ class Solution :
12+ def hasCycle_on (self , head : Optional [ListNode ]) -> bool :
13+ """
14+ [Complexity]
15+ - TC: O(n)
16+ - SC: O(n)
17+
18+ [Approach]
19+ hash table로 visited 노드를 기록한다.
20+ """
21+ curr = head
22+ visited = set ()
23+
24+ while curr :
25+ if curr in visited :
26+ return True
27+
28+ visited .add (curr )
29+ curr = curr .next
30+
31+ return False
32+
33+ def hasCycle (self , head : Optional [ListNode ]) -> bool :
34+ """
35+ [Complexity]
36+ - TC: O(n)
37+ - SC: O(1)
38+
39+ [Approach]
40+ Floyd’s Cycle Detection 알고리즘을 사용한다.
41+ linked list에서 slow (1칸씩 전진) & fast (2칸씩 전진) runner를 이용하면,
42+ - slow와 fast가 만난다면 cyclic
43+ - 만나지 않은 채로 fast가 끝에 도달하면 not cyclic
44+ 이다.
45+ """
46+ slow = fast = head
47+
48+ while fast and fast .next :
49+ slow = slow .next
50+ fast = fast .next .next
51+
52+ if slow == fast :
53+ return True
54+
55+ return False
You can’t perform that action at this time.
0 commit comments