File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change
1
+ # Definition for singly-linked list.
2
+ # class ListNode:
3
+ # def __init__(self, x):
4
+ # self.val = x
5
+ # self.next = None
6
+
7
+ """
8
+ TC: O(n)
9
+ SC: O(n)
10
+ """
11
+ class Solution :
12
+ def hasCycle (self , head : Optional [ListNode ]) -> bool :
13
+ visited = set ()
14
+ while head :
15
+ # 해당 노드 이미 방문한 적 있으면
16
+ if head in visited :
17
+ return True
18
+ # 방문한 적 없으면 set에 넣기
19
+ visited .add (head )
20
+ # 다음 노드로 이동
21
+ head = head .next
22
+
23
+ # cycle이 없음
24
+ return False
25
+
26
+ """
27
+ The tortoise and hare
28
+
29
+ TC: O(n)
30
+ SC: O(1)
31
+ """
32
+ class Solution :
33
+ def hasCycle (self , head : Optional [ListNode ]) -> bool :
34
+ slow , fast = head , head
35
+ while fast and fast .next :
36
+ slow = slow .next
37
+ fast = fast .next .next
38
+ if slow == fast :
39
+ return True
40
+ return False
You can’t perform that action at this time.
0 commit comments