[leetcode-python3] 141. Linked List Cycle

1860 ワード

141. Linked List Cycle - python3
Given head, the head of a linked list, determine if the linked list has a cycle in it.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to. Note that pos is not passed as a parameter.
Return true if there is a cycle in the linked list. Otherwise, return false.
My Answer 1: Accepted (Runtime: 52 ms/Memory Usage: 17.2 MB)
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def hasCycle(self, head: ListNode) -> bool:
        if head is None or head.next is None:
            return False
        
        hA = head
        hB = head.next
        
        while hA!=hB:
            if hB is None or hB.next is None:
                return False
            hA = hA.next
            hB = hB.next.next
        
        return True
昨日習った卒倒寸前の超単純コードを参考に始まりました
コードの核心は、スペースを移動するポインタと、一歩先に進むポインタだと思います.
hbはこのように一瞬にして通り過ぎた.next.nextを作る
head.nextがない場合は常にエラーが発生するため,条件文で多くの制限が行われている.
Other Answer 1: (Runtime: 48 ms/Memory Usage: 17.6 MB)
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def hasCycle(self, head: ListNode) -> bool:
        s=set()
        while head is not None:
            if head not in s:
                s.add(head)
            else:
                return True
            head=head.next
        return False
ハッシュ・セットの使用方法
setの中にあればきっとtrue
開いているのはポインタですが当たっているものもあります...
set()を使うと分かりやすく、簡単になります