File tree Expand file tree Collapse file tree 1 file changed +14
-26
lines changed
0142-linked-list-cycle-ii Expand file tree Collapse file tree 1 file changed +14
-26
lines changed Original file line number Diff line number Diff line change 1- # Approach 2 - Floyd's Cycle Finding Algorithm
2-
3- # Time: O(n), Space: O(1)
1+ # Approach 2: Floyd's Tortoise and Hare Algorithm
42
3+ # Time: O(n)
4+ # Space: O(1)
55
66# Definition for singly-linked list.
77# class ListNode:
1010# self.next = None
1111
1212class Solution :
13-
14- def get_intersect (self , head ):
15- slow = head
16- fast = head
17-
18- while fast is not None and fast .next is not None :
13+ def detectCycle (self , head : Optional [ListNode ]) -> Optional [ListNode ]:
14+ slow = fast = head
15+
16+ while fast and fast .next :
1917 slow = slow .next
2018 fast = fast .next .next
19+
2120 if slow == fast :
21+ # Found intersection, find cycle start
22+ slow = head
23+
24+ while slow != fast :
25+ slow = slow .next
26+ fast = fast .next
2227 return slow
23-
2428 return None
25-
26- def detectCycle (self , head : Optional [ListNode ]) -> Optional [ListNode ]:
27- if head is None :
28- return None
29-
30- intersect = self .get_intersect (head )
31- if intersect is None :
32- return None
3329
34- ptr1 = head
35- ptr2 = intersect
36- while ptr1 != ptr2 :
37- ptr1 = ptr1 .next
38- ptr2 = ptr2 .next
39-
40- return ptr1
41-
You can’t perform that action at this time.
0 commit comments