我看样例给的没有重复的数字,然后又看了看数据范围,我还是义无反顾选择了相信自己
我就知道这题有诈!

前几天碰到了哈希,感觉用起来还是很快的,于是准备用哈希
但是写着写着感觉用列表就够了
便有了如下代码:

def hasCycle(self , head: ListNode) -> bool:
    nodeList = []
    while head:
        if head in nodeList:
            return True
    
        nodeList.append(head)
        head = head.next

    return False

但是,耗时太长了,便用哈希表又来了一遍
代码如下:

def hasCycle(self , head: ListNode) -> bool:
    hashtable = dict()
    i = 0
    while head:
        if head in hashtable:
            return True

        hashtable[head] = 1
        i += 1
        head = head.next

    return False

虽然这样写已经ok了,但是不满足空间复杂度
于是我跑去看了评论区,学到了快慢指针
代码如下:

def hasCycle(self , head: ListNode) -> bool:
    slow, fast = head, head
    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next

        if slow == fast:
            return True

    return False

今天又学到新知识了 真是辛苦我自己了呢