题目
代码
执行用时:48 ms, 在所有 Python3 提交中击败了18.68% 的用户
内存消耗:15.7 MB, 在所有 Python3 提交中击败了73.78% 的用户
通过测试用例:18 / 18
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]
【方法2】
执行用时:32 ms, 在所有 Python3 提交中击败了94.64% 的用户
内存消耗:15.7 MB, 在所有 Python3 提交中击败了73.78% 的用户
通过测试用例:18 / 18
class Solution:
def copyRandomList(self, head: 'Node') -> 'Node':
if not head: return
cur = head
while cur:
newNode=Node(cur.val)
newNode.next=cur.next
cur.next=newNode
cur=newNode.next
cur=head
while cur:
if cur.random:
cur.next.random=cur.random.next
cur=cur.next.next
ans=cur=head.next
pre=head
while cur.next:
pre.next=pre.next.next
cur.next=cur.next.next
pre=pre.next
cur=cur.next
pre.next=None
return ans