forked from algorithm016-algorithm016/algorithm016
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathleetcode142.环形链表II.py
48 lines (41 loc) · 1.17 KB
/
leetcode142.环形链表II.py
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
#方法一、快慢指针,Floyed方法
#超过68%
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def getIntersect(self, head):
tortoise = hare = head
while hare and hare.next:
tortoise = tortoise.next
hare = hare.next.next
if tortoise == hare:
return tortoise
return None
def detectCycle(self, head: ListNode) -> ListNode:
hare = self.getIntersect(head)
tortoise = head
if not hare: return None
while tortoise:
if tortoise == hare:
return tortoise
tortoise = tortoise.next
hare = hare.next
#方法二、哈希
#超过68%
# 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:
hashMap = {}
while head:
if hashMap.get(head) is not None:
return head
hashMap[head] = 1
head = head.next
return None