安全プランを証明するために - 複製複雑なリスト

タイトル説明

複合入力リスト(各ノードは、ノードの値を有し、二つのポインタ、次のノードへの1つのポインティング、他のノードへの特別なポインタ)は、複雑なリストの複製の頭部後の値を返します。(出力結果は、パラメータノード参照を返さないことに注意、それ以外のプログラムは、直接、空の宣告質問に戻ります)

解決するために暴力:

最初から最後までまずトラバース、空のリストのための新しいランダムポインタ。私たちは、すべての二つのリストリスト内の2つのノードを持つために維持しました。

次いで、リスト、各ノードを付与する新しいランダムな基準にリンクされたリストの元のリストのランダムな位置に応じて、最初から最後までトラバース。

class Solution:
    # 返回 RandomListNode
    def Clone(self, pHead):
        if not pHead:
            return None
        node = RandomListNode(pHead.label)
        head = node
        pHead_s = pHead
        nodes = [pHead]
        nodes_copy = [node]
        pHead = pHead.next
        
        while pHead:
            node.next = RandomListNode(pHead.label)
            node = node.next
            nodes.append(pHead)
            nodes_copy.append(node)
            pHead = pHead.next
        head_s = head
        while pHead_s:
            if pHead_s.random:
                head_s.random = nodes_copy[nodes.index(pHead_s.random)]
            pHead_s = pHead_s.next
            head_s = head_s.next
        return head

最適化:

上記暴力の時間計算量はO(N ^ 2)であり、空間的な複雑さはO(N)であります

オフ牛に答えを読み取る、時間複雑度はO(N)は、空間複雑度はO(1)
キャプション

class Solution:
    def Clone(self, pHead):
        pHead_s = pHead
        while pHead_s:
            temp = pHead_s.next
            pHead_s.next = RandomListNode(pHead_s.label)
            pHead_s.next.next = temp
            pHead_s = pHead_s.next.next
        
        pHead_s = pHead
        while pHead_s:
            if pHead_s.random:
                pHead_s.next.random = pHead_s.random.next
            pHead_s = pHead_s.next.next
        
        pHead_s = pHead
        head_s = pHead_s.next
        head = head_s
        while head_s.next:
            pHead_s.next = pHead_s.next.next
            head_s.next = head_s.next.next
            pHead_s = pHead_s.next
            head_s = head_s.next
        return head

 

公開された82元の記事 ウォンの賞賛2 ビュー4363

おすすめ

転載: blog.csdn.net/qq_22498427/article/details/104750364