Copy List with Random Pointer 带随机指针的链表的拷贝
来源:互联网 发布:华为sa1456c改mac 编辑:程序博客网 时间:2024/06/04 18:50
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.
这道题其实还蛮绕的
假设链表为1->3->2->5首先进行普通的拷贝
接着:假设1的随之指针指向2.
那么新生成的链表1->3->2->5怎么知道让1指向2呢?
需要几步:
1. 1 知道指向2
2. 即知道值为2 指向index = 2的节点(从0开始) hashmap: index to node
3. 如何知道index = 2的节点呢?假设原来的1指向2 这个节点,要是2这个节点又知道自己的下标 就可了。hashmap: node to index
运行时间:
代码:
public class CopyListwithRandomPointer { public RandomListNode copyRandomList(RandomListNode head) { Map<RandomListNode, Integer> nodeToIndexMap = new HashMap<>(); Map<Integer, RandomListNode> indexToNodeMap = new HashMap<>(); RandomListNode fakeHead = new RandomListNode(-1), fakeNode = fakeHead; RandomListNode cur = head; int i = 0; while (cur != null) { nodeToIndexMap.put(cur, i); fakeNode.next = new RandomListNode(cur.label); fakeNode = fakeNode.next; cur = cur.next; i++; } i = 0; RandomListNode newcur = fakeHead.next; while (newcur != null) { indexToNodeMap.put(i, newcur); newcur = newcur.next; i++; } newcur = fakeHead.next; cur = head; while (newcur != null) { newcur.random = indexToNodeMap.get(nodeToIndexMap.get(cur.random)); newcur = newcur.next; cur = cur.next; } return fakeHead.next; }}
1 0
- Copy List with Random Pointer 带随机指针的链表的拷贝
- 附有随机结点指针的链表的深度拷贝 Copy List with Random Pointer
- Copy List with Random Pointer 带随机指针链表的复制
- [LintCode] 复制带随机指针的链表 Copy List with Random Pointer
- 105.Copy List with Random Pointer-复制带随机指针的链表(中等题)
- Copy List with Random Pointer 复制有随机指针的链表@LeetCode
- LeetCode | Copy List with Random Pointer(赋值带有随机指针的链表)
- Copy List with Random Pointer复制带有随机指针的链表
- LeetCode OJ 之 Copy List with Random Pointer(复制含有随机指针的链表)
- LeetCode138 Copy List with Random Pointer(深度复制带有随机指针的链表) Java题解
- 【LeetCode】138.Copy List with Random Pointer 复制带有随机指针的链表
- [LeetCode]—Copy List with Random Pointer 深度复制带“任意指针”的链表
- 【LeetCode-面试算法经典-Java实现】【138-Copy List with Random Pointer(拷贝有随机指针的单链表)】
- 【LeetCode-面试算法经典-Java实现】【143-Copy List with Random Pointer(有随机指针的链表复制)】
- LeetCode之复制有random指针的链表Copy List with Random Pointer
- LeetCode(Copy List with Random Pointer) 复杂链表的深拷贝
- LeetCode 138. Copy List with Random Pointer(拷贝随机指针)
- Leetcode Copy List with Random Pointer 拷贝链表
- PYTHON_DAY_12_20160610
- hdu HDU 3555 Bomb
- 关于linearLaout的权重,随手笔记
- 高斯模糊的算法
- PYTHON_DAY_13_201606011
- Copy List with Random Pointer 带随机指针的链表的拷贝
- 【每天学一点】C++基础5
- Android自定义ListView
- 一个例子带你深入理解ViewPager之广告轮播条的实现
- Java对象初始化
- Srping源码深度解析(二)容器的基本用法
- IOError: No wkhtmltopdf executable found: ""
- 国外程序员收集整理的PHP资源大全
- 用oracle安装包自带的unzip文件 解压oracle的zip安装包