请实现 copyRandomList 函数,复制一个复杂链表。在复杂链表中,每个节点除了有一个 next 指针指向下一个节点,还有一个
random 指针指向链表中的任意节点或者 null。
示例 1:
输入:head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
输出:[[7,null],[13,0],[11,4],[10,2],[1,0]]
示例 2:
输入:head = [[1,1],[2,1]]
输出:[[1,1],[2,1]]
示例 3:
输入:head = [[3,null],[3,0],[3,null]]
输出:[[3,null],[3,0],[3,null]]
提示:
-10000 <= Node.val <= 10000 Node.random 为空(null)或指向链表中的节点。 节点数目不超过 1000 。
方案一:
"""
# Definition for a Node.
class Node:
def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
self.val = int(x)
self.next = next
self.random = random
"""
class Solution:
def copyRandomList(self, head: 'Node') -> 'Node':
l = Node(0)
p = l
origin = head
dp = {}
mermory = {}
i = 0
data = []
while origin:
data.append(origin.val)
origin.val = i
i+=1
origin = origin.next
origin = head
while origin:
l.next = Node(0)
l = l.next
l.val = origin.val
if(origin.random != None):dp[origin.val] = origin.random.val
else: dp[origin.val] = None
mermory[l.val] = l
origin = origin.next
l = p.next
i = 0
while l:
if(dp[l.val] == None):l.random = None
else:l.random = mermory[dp[l.val]]
l.val = data[i]
l = l.next
i+=1
return p.next
方案二:
虽然很简短,但是效率比上一个低,离谱。。。
class Solution:
def copyRandomList(self, head: 'Node') -> 'Node':
if not head: return
dic = {}
# 3. 复制各节点,并建立 “原节点 -> 新节点” 的 Map 映射
cur = head
while cur:
dic[cur] = Node(cur.val)
cur = cur.next
cur = head
# 4. 构建新节点的 next 和 random 指向
while cur:
dic[cur].next = dic.get(cur.next)
dic[cur].random = dic.get(cur.random)
cur = cur.next
# 5. 返回新链表的头节点
return dic[head]