环形链表判断

方法一:

哈希表

时间复杂度:O(n)

空间复杂度:O(n)

class Solution:
    def hasCycle(self, head: ListNode) -> bool:
        dict = {}
        while head:
            if head in dict:
                return True
            else:
                dict.setdefault(head,1)
                head = head.next
        return False

方法二:

快慢指针

时间复杂度:O(n)

空间复杂度:O(1)

class Solution:
    def hasCycle(self, head: ListNode) -> bool:
        slow = head
        fast = head
        while  fast and fast.next:
            slow = slow.next
            fast = fast.next.next
            if slow == fast:
                return True
        return False

猜你喜欢

转载自www.cnblogs.com/gugu-da/p/13190976.html