首页 > 其他 > 详细

环形链表判断

时间:2020-06-25 09:50:22      阅读:61      评论:0      收藏:0      [点我收藏+]

方法一:

哈希表

时间复杂度: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

环形链表判断

原文:https://www.cnblogs.com/gugu-da/p/13190976.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!