leetcode-141. リングチェーンテーブルpython版の4つの解決方法

9837 ワード

チェーンテーブルを指定し、チェーンテーブルにリングがあるかどうかを判断します.
与えられたチェーンテーブルのループを表すために、整数posを使用してチェーンテーブルの最後にチェーンテーブルに接続された位置を表します(インデックスは0から始まります).posが-1の場合、チェーンテーブルにリングはありません.
例1:入力:head=[3,2,0,-4],pos=1出力:true解釈:チェーンテーブルに2番目のノードに接続されたループがあります.
例2:入力:head=[1,2]、pos=0出力:true解釈:チェーンテーブルにループがあり、その末尾が最初のノードに接続されています.
例3:入力:head=[1]、pos=-1出力:false解釈:チェーンテーブルにリングがありません.
ステップアップ:O(1)(すなわち定数)メモリでこの問題を解決できますか?
以下は私のpython版の4つの解法です.
1つ目の方法:記憶化検索法、直観的に理解しやすい
# 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
        """
        if not head:
            return False
        node_list = list()
        while head:
            if head in node_list:
                return True
            else:
                node_list.append(head)
            head = head.next
        return False
        

第2の方法:速い遅い指針法、占有空間が小さくて、速度が速い
# 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
        """
        if head is None or head.next is None:
            return False
        slow = head
        fast = head.next
        while fast and fast.next:
            if slow == fast:
                return True
            slow = slow.next
            fast = fast.next.next
        return False    

第三の方法:ポインタ自己認識法
# 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
        """
        if head is None or head.next is None:
            return False
        cur = head
        next = head
        while cur:
            next = cur.next
            if cur.next == cur:
                return True
            else:
                cur.next = cur
            cur = next
        return False

第四の方法:ノード賦値法、比較的簡単な暴力
# 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
        """
        while head:
            if head.val == "cycle":
                return True
            else:
                head.val = "cycle"
            head = head.next
        return False