-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0142M. Linked List Cycle II.py
More file actions
61 lines (55 loc) · 1.77 KB
/
0142M. Linked List Cycle II.py
File metadata and controls
61 lines (55 loc) · 1.77 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
54
55
56
57
58
59
60
61
#Runtime: 180 ms, faster than 5.01% of Python3 online submissions for Linked List Cycle II.
#Memory Usage: 17 MB, less than 95.45% of Python3 online submissions for Linked List Cycle II.
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def detectCycle(self, head: ListNode) -> ListNode:
if not head or not head.next:
return None
fast = head.next
ind = slow = head
cand = []
while fast != slow:
try:
fast = fast.next.next
slow = slow.next
except:
return None
while slow not in cand:
cand.append(slow)
slow = slow.next
while ind not in cand:
ind = ind.next
return ind
#Runtime: 984 ms, faster than 5.01% of Python3 online submissions for Linked List Cycle II.
#Memory Usage: 17.2 MB, less than 55.16% of Python3 online submissions for Linked List Cycle II.
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution2:
def detectCycle(self, head: ListNode) -> ListNode:
if not head or not head.next:
return None
fast = head.next.next
slow = head.next
ind = head
while fast != slow:
try:
fast = fast.next.next
slow = slow.next
except:
return None
while ind != slow:
slow = slow.next
while slow != fast:
if ind == slow:
return ind
else:
slow = slow.next
ind = ind.next
return ind