leetcood学习笔记-141-环形列表

题目描述:

方法一:

class Solution(object):
    def hasCycle(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        while head:
            if head.val == "daafas":
                return True
            else:
                head.val = "daafas":
            head = head.next
        return False

 

法二:判断某个元素是否在集合中只有O(1),

class Solution(object):
    def hasCycle(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        save = set()
        cur = head 
        while cur is not None:
            if cur in save:
                return True
            else:
                save.add(cur)
                cur = cur.next
        return False 

 法三:指针追逐: O(n),O(1)

class Solution(object):
    def hasCycle(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        if not head or not head.next :
            return False
        a,b = head,head.next
        while a!=b:
            if  b == None or b.next == None:
                return False
            else:
                a = a.next
                b = b.next.next
        return True
        // 找环节点的方法:
        // slow 走过 k 步,slow 的情人 fast 走过 2k 步他们在巴厘岛邂逅。
        // 意味着 slow 再走 k 步,一定又会回到巴厘岛。
        // slow 从巴厘岛出发,slow 的老公 green 先生从起点出发,两人同时走 k 步,最终会在巴厘岛相遇。这样就找到了环节点。
        // 我们并不关心 k 的值是多少,因为他们一定会在巴厘岛相遇。

 

posted @ 2019-03-18 19:45  oldby  阅读(632)  评论(0编辑  收藏  举报