leetcode 138. Copy List with Random Pointer 链表复制 + HashMap
来源:互联网 发布:搜索不到淘宝店铺 编辑:程序博客网 时间:2024/06/06 05:13
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.
本题题意就是复制链表,注意使用HashMap等结构保存相关信息,这样更加方便。
代码如下:
import java.util.HashMap;import java.util.Map;/*class RandomListNode { int label; RandomListNode next, random; RandomListNode(int x) { this.label = x; }};*//* * 这个是用一个map映射关系来获取相关的信息,这样避免了直接复制的遍历开销 * */public class Solution{ public RandomListNode copyRandomList(RandomListNode head) { if(head == null) return head; Map<Integer, RandomListNode> map = new HashMap<>(); Map<RandomListNode,Integer> remap = new HashMap<>(); Map<Integer, RandomListNode> newMap = new HashMap<>(); RandomListNode newHead = new RandomListNode(-1); RandomListNode iter = head , newIter = newHead; int count = 0; while(iter!=null) { newIter.next = new RandomListNode(iter.label); map.put(count, iter.random); remap.put(iter, count); newMap.put(count,newIter.next); newIter = newIter.next; iter =iter.next; count++; } newIter = newHead.next; count = 0; while(newIter!=null) { RandomListNode ran = map.get(count); if(ran==null) newIter.random = null; else { int key = remap.get(ran); newIter.random = newMap.get(key); } newIter = newIter.next; count++; } return newHead.next; }}
阅读全文
0 0
- leetcode 138. Copy List with Random Pointer 链表复制 + HashMap
- 【LeetCode】138.Copy List with Random Pointer 复制带有随机指针的链表
- LeetCode之复制有random指针的链表Copy List with Random Pointer
- [LeetCode]Copy List with Random Pointer &Clone Graph 复杂链表的复制&图的复制
- LeetCode 138. Copy List with Random Pointer
- [Leetcode] 138. Copy List with Random Pointer
- LeetCode 138. Copy List with Random Pointer
- [leetcode] 138. Copy List with Random Pointer
- LeetCode 138. Copy List with Random Pointer
- LeetCode 138. Copy List with Random Pointer
- leetcode.138. Copy List with Random Pointer
- LeetCode-138.Copy List with Random Pointer
- Leetcode 138. Copy List with Random Pointer
- [Leetcode]138. Copy List with Random Pointer
- LeetCode 138. Copy List with Random Pointer
- [LeetCode] 138. Copy List with Random Pointer
- [LeetCode]138. Copy List with Random Pointer
- LeetCode 138. Copy List with Random Pointer
- Unity 数值太大导致场景加载卡死问题
- 读书经验
- 分治算法之排序和逆序对
- win7 64位Anaconda3下安装Pytorch教程
- Python3中byte和string之间各种编码转换
- leetcode 138. Copy List with Random Pointer 链表复制 + HashMap
- 谈谈对Spring的理解
- RHEL 6.5 安装 grid 报错:CRS-4124
- Log4J,在踩坑中升级版本
- 删除数字
- Linux常用命令
- 树和二叉树 概念整理
- JS技术(5)---String常用函数(slice,substr,substring)运用
- 笔试_多线程