1. 程式人生 > >【python3】leetcode 141. Linked List Cycle (easy)

【python3】leetcode 141. Linked List Cycle (easy)

141. Linked List Cycle (easy) 

Given a linked list, determine if it has a cycle in it.

To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.

 

Example 1:

Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle in the linked list, where tail connects to the second node.

Example 2:

Input: head = [1,2], pos = 0
Output: true
Explanation: There is a cycle in the linked list, where tail connects to the first node.

Example 3:

Input: head = [1], pos = -1
Output: false
Explanation: There is no cycle in the linked list.

 

Follow up:

Can you solve it using O(1) (i.e. constant) memory?

solution翻譯:

想象一下兩個跑步者以不同的速度在賽道上跑步。當賽道實際上是一個圓圈時會發生什麼?

演算法

通過考慮不同速度的兩個指標 - 慢速指標和快速指標,可以將空間複雜度降低到O(1)。慢速指標一次移動一步,而快速指標一次移動兩步。

如果列表中沒有迴圈,則快速指標最終將到達結尾,在這種情況下我們可以返回false。

現在考慮一個迴圈列表,並想象慢速和快速指標是圍繞圓形軌道的兩個跑步者。快速跑步者最終會遇到慢跑者。為什麼?考慮這種情況(我們將其命名為案例A) - 快速跑步者僅落後於慢跑者一步。在下一次迭代中,它們分別增加一步和兩步並相互會合。

其他案件怎麼樣?例如,我們還沒有考慮過快速跑步者落後慢跑者兩到三步的情況。這很簡單,因為在下一個或下一個下一次迭代中,這種情況將簡化為上面提到的情況A.

 

龜兔賽跑原理,一個走1步一個走2步,如果有環總會趕上,如果slow或fast已經走到末尾 就說明沒有環 

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def hasCycle(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        #O(1) memory
        if not head or not head.next:return False
        slow = head
        fast = head.next
        while(slow != fast):
            if not slow.next or not fast.next or not fast.next.next:return False
            
            slow = slow.next
            fast = fast.next.next
            if slow == fast:return True
        return True