C/C++教程

leetcode138. Copy List with Random Pointer

本文主要是介绍leetcode138. Copy List with Random Pointer,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

Construct a deep copy of the list. 

The linked list is represented in the input/output as a list of n nodes. Each node is represented as a pair of [val, random_index] where:

  • val: an integer representing Node.val
  • random_index: the index of the node (range from 0 to n-1) that the random pointer points to, or null if it does not point to any node.

Your code will only be given the head of the original linked list.

Example 1:

Input: head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
Output: [[7,null],[13,0],[11,4],[10,2],[1,0]]
解法一:
建一个dict,先对每个点copy一个点存在dict的值里,再对每个dict的值,把next和random加上去。
注意:dic[i]如果没有值就会报错,所以这里用dic.get(i),防止有的点random是空,或者最后一个点next是空。
time: O(2n) 
space: O(n)


"""
# 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]':
        dic = {}
        node = cur = head
        while node:
            dic[node] = Node(node.val)
            node = node.next
        while cur:
            dic[cur].next = dic.get(cur.next)
            dic[cur].random = dic.get(cur.random)
            cur = cur.next
        return dic.get(head)
        

 

这篇关于leetcode138. Copy List with Random Pointer的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!