鱼C论坛

 找回密码
 立即注册
查看: 2407|回复: 0

[学习笔记] Leetcode 138. Copy List with Random Pointer

[复制链接]
发表于 2020-9-16 03:48:49 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 Seawolf 于 2020-9-16 03:54 编辑

A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.

Return 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) where random pointer points to, or null if it does not point to any node.


Example 1:

Screenshot from 2020-09-15 15-47-34.png

Input: head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
Output: [[7,null],[13,0],[11,4],[10,2],[1,0]]

Example 2:

Screenshot from 2020-09-15 15-47-39.png

Input: head = [[1,1],[2,1]]
Output: [[1,1],[2,1]]

Example 3:

Screenshot from 2020-09-15 15-47-45.png

Input: head = [[3,null],[3,0],[3,null]]
Output: [[3,null],[3,0],[3,null]]
Example 4:

Input: head = []
Output: []
Explanation: Given linked list is empty (null pointer), so return null.


Constraints:

-10000 <= Node.val <= 10000
Node.random is null or pointing to a node in the linked list.
Number of Nodes will not exceed 1000.
"""
# 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: 'Node') -> 'Node':
        if head == None: return head
        hashmap = collections.defaultdict(Node)
        curt = head
        
        while curt:
            new_node = Node(curt.val)
            hashmap[curt] = new_node
            curt = curt.next
        
        curt = head
        
        while curt:
            next = curt.next
            random = curt.random
            
            if next != None:
                hashmap[curt].next = hashmap[next]
            if random != None:
                hashmap[curt].random = hashmap[random]
            curt = curt.next
        
        return hashmap[head]

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-11-22 18:32

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表