-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0142-linked-list-cycle-ii.py
More file actions
53 lines (41 loc) · 1.14 KB
/
0142-linked-list-cycle-ii.py
File metadata and controls
53 lines (41 loc) · 1.14 KB
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
46
47
48
49
50
51
52
53
# time complexity: O(n)
# space complexity: O(n)
from typing import Optional
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
nodeSeen = set()
node = head
while node:
if node in nodeSeen:
return node
nodeSeen.add(node)
node = node.next
return None
# time complexity: O(n)
# space complexity: O(1)
class Solution:
def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
slow = head
fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
break
if not fast or not fast.next:
return None
fast = head
while slow != fast:
slow = slow.next
fast = fast.next
return slow
head = ListNode(3)
head.next = ListNode(2)
head.next.next = ListNode(0)
head.next.next.next = ListNode(-4)
head.next.next.next.next = head.next
print(Solution().detectCycle(head))