鱼C论坛

 找回密码
 立即注册
查看: 1967|回复: 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.

  1. """
  2. # Definition for a Node.
  3. class Node:
  4.     def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
  5.         self.val = int(x)
  6.         self.next = next
  7.         self.random = random
  8. """

  9. class Solution:
  10.     def copyRandomList(self, head: 'Node') -> 'Node':
  11.         if head == None: return head
  12.         hashmap = collections.defaultdict(Node)
  13.         curt = head
  14.         
  15.         while curt:
  16.             new_node = Node(curt.val)
  17.             hashmap[curt] = new_node
  18.             curt = curt.next
  19.         
  20.         curt = head
  21.         
  22.         while curt:
  23.             next = curt.next
  24.             random = curt.random
  25.             
  26.             if next != None:
  27.                 hashmap[curt].next = hashmap[next]
  28.             if random != None:
  29.                 hashmap[curt].random = hashmap[random]
  30.             curt = curt.next
  31.         
  32.         return hashmap[head]
复制代码

本帖被以下淘专辑推荐:

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

使用道具 举报

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

本版积分规则

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

GMT+8, 2024-4-25 12:04

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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