題目:原題連結(中等)
标簽:連結清單
解法 | 時間複雜度 | 空間複雜度 | 執行用時 |
---|---|---|---|
Ans 1 (Python) | – | 52ms (42.35%) | |
Ans 2 (Python) | O ( N ) O(N) O(N) | 36ms (98.50%) | |
Ans 3 (Python) |
def copyRandomList(self, head: 'Node') -> 'Node':
import copy
return copy.deepcopy(head)
def copyRandomList(self, head: 'Node') -> 'Node':
# 處理特殊情況
if not head:
return None
# 生成節點并存儲在字典中
hashmap = {}
node = head
while node:
hashmap[node] = Node(node.val)
node = node.next
# 生成next和random指針
node = head
while node:
if node.next:
hashmap[node].next = hashmap[node.next]
if node.random:
hashmap[node].random = hashmap[node.random]
node = node.next
# 傳回結果
return hashmap[head]