LeetCode 138題:複製複雜鏈表(快過98.49%,空間利用少於100%的python解法)

題目

原題如下

138. Copy List with Random Pointer

A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
Return a deep copy of the list.

解釋

題目是讓大家複製一個複雜鏈表。這個鏈表爲什麼複雜呢,因爲每一個節點除了一個next指針,還多了一個隨機指針。這個隨機指針可能爲空,也可能指向任意一個節點。

解法

這個題目前沒有發現任何可以取巧的解法。必須得一步一步踏踏實實的解。先按照next指針構造好新的鏈表。在構造的同時記錄新的節點和舊的節點的對應關係,然後在依次初始化random指針。
可見思路非常簡單,但是按照這個思路寫的代碼表現如下:

Runtime: 36 ms, faster than 98.49% of Python3 online submissions for Copy List with Random Pointer.
Memory Usage: 14.7 MB, less than 100.00% of Python3 online submissions for Copy List with Random Pointer.

由此我們知道這道題彷彿沒有什麼特別取巧的解法或者思路了。
代碼如下:

"""
# Definition for a Node.
class Node:
    def __init__(self, val, next, random):
        self.val = val
        self.next = next
        self.random = random
"""
class Solution:
    def copyRandomList(self, head: 'Node') -> 'Node':
        if not head:
            return None
        
        headN = Node(head.val, None, None)
        O2N = {head: headN}
        
        nnPre = headN
        no = head.next
        while no != None:
            nn = Node(no.val, None, None)
            nnPre.next, nnPre = nn, nn
            O2N[no] = nn
            
            no = no.next
            
        nn = headN
        no = head
        while nn:
            if no.random:
                nn.random = O2N[no.random]
            else:
                nn.random = None
            nn, no = nn.next, no.next
            
        return headN

我將我寫的LeetCode代碼都記錄在了GitHub,歡迎大家去逛逛

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章