Posted on 2023-09-05 13:51
Uriel 阅读(27)
评论(0) 编辑 收藏 引用 所属分类:
数据结构 、
闲来无事重切Leet Code
实现链表的深度copy,链表除了next指针,每个节点还有一个random指针,指向任意节点,copy的时候也要还原
python的dict的妙用
1 #138
2 #Runtime: 28 ms (Beats 92.87%)
3 #Memory: 13.9 MB (Beats 70.54%)
4
5 """
6 # Definition for a Node.
7 class Node:
8 def __init__(self, x, next=None, random=None):
9 self.val = int(x)
10 self.next = next
11 self.random = random
12 """
13
14 class Solution(object):
15 def copyRandomList(self, head):
16 """
17 :type head: Node
18 :rtype: Node
19 """
20 dic = {None:None}
21 cur = head
22 while cur:
23 dic[cur] = Node(cur.val)
24 cur = cur.next
25 cur = head
26 while cur:
27 cp = dic[cur]
28 cp.next = dic[cur.next]
29 cp.random = dic[cur.random]
30 cur = cur.next
31 return dic[head]