Leetcode 138. Copy List with Random Pointer(python)

Leetcode 138. Copy List with Random Pointer

题目

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.valrandom_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.
在这里插入图片描述

解析

刚看到这道题目的时候理解错了,以为node.random是一个数字,主要是他这个例子的表述方法有点让人误导。然后这道题看Leetcode的官方解法一脸懵,不太懂为啥这个题目要这么麻烦,后面看到了一种不那么麻烦的解法,这边就暂时先用这种不那么麻烦的解法,等二刷再研究leetcode的官方解法吧

解法:利用hashtable

这种解法的关键思想是,由于每个node的random point可能会指向任何一个node,所以在一次顺序遍历list中很难直接将random point也做好。为了更加方便的寻找random pointer指向的节点,可以把原来的node作为key,copy后的node作为值的方式存入hashtable。具体做法如下:

  • 首先第一次顺序遍历原链表,构造一个传统意义上只有next的链表,同时将原node和copy_node以键值对方式储存
  • 再次遍历原链表࿰
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值