题目描述:
给定一个链表的头节点 head
,返回链表开始入环的第一个节点。 如果链表无环,则返回 null
。
解法一:哈希表
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
# 哈希表 O(m+n)
class Solution:
def detectCycle(self, head: ListNode) -> ListNode:
if head == None:
return None
p = head
hash_map = set()
while p.next != None:
if p in hash_map:
return p
hash_map.add(p)
p = p.next
return None
提交一直失败:报错:Your returned value is not a ListNode type
最后的解决方案是一定要保持ListNode类是被注释状态,不能自己解开注释。
解法二:快慢指针
附上我认为leetcode讲解很清晰的一位大佬: