原题
https://leetcode.cn/problems/copy-list-with-random-pointer/description/
思路
字典
复杂度
时间:O(n)
空间:O(n)
Python代码
"""
# 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: 'Optional[Node]') -> 'Optional[Node]':
if not head:
return None
dic = dict()
cur = head
while cur:
node = Node(cur.val)
dic[cur] = node
cur = cur.next
cur = head
while cur:
node = dic[cur]
node.next = dic.get(cur.next)
node.random = dic.get(cur.random)
cur = cur.next
return dic[head]
Go代码
/**
* Definition for a Node.
* type Node struct {
* Val int
* Next *Node
* Random *Node
* }
*/
func copyRandomList(head *Node) *Node {
if head == nil {
return nil
}
// 字典存储原节点和复制的节点
m := map[*Node]*Node{}
cur := head
for cur != nil {
node := &Node{Val: cur.Val}
m[cur] = node
cur = cur.Next
}
cur = head
for cur != nil {
node := m[cur]
node.Next = m[cur.Next]
node.Random = m[cur.Random]
cur = cur.Next
}
return m[head]
}
随机链表复制方法解析
776

被折叠的 条评论
为什么被折叠?



