-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path141-Linked-List-Cycle.py
More file actions
45 lines (34 loc) · 946 Bytes
/
Copy path141-Linked-List-Cycle.py
File metadata and controls
45 lines (34 loc) · 946 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
# region Floyd's Cycle Finding Algorithm (slow/fast pointers)
class Solution:
# Space O(1)
# Time O(n)
def hasCycle(self, head: Optional[ListNode]) -> bool:
if not head:
return False
slow, fast = head, head.next
while fast and fast.next:
if slow == fast:
return True
slow = slow.next
fast = fast.next.next
return False
# endregion
# region Hash Table / Set Solution
class Solution:
# Space O(n)
# Time O(n)
def hasCycle(self, head: Optional[ListNode]) -> bool:
mySet = set()
while head is not None:
if head in mySet:
return True
else:
mySet.add(head)
head = head.next
return False
# endregion