[leetcode]Copy List with Random Pointer
来源:互联网 发布:java初级工程师简历 编辑:程序博客网 时间:2024/06/08 00:52
解题思路1:
一个深度的 copy。
1,如果只有next,那就好办了,一个挨着一个的copy就好
2,这里有random,最理想的就是 random指哪儿,我们就知道那里对应的copy在哪儿。 这个对应,就是map,立刻想到的就是hashmap
/** * Definition for singly-linked list with a random pointer. * class RandomListNode { * int label; * RandomListNode next, random; * RandomListNode(int x) { this.label = x; } * }; */public class Solution { public RandomListNode copyRandomList(RandomListNode head) { if (head == null) return head; Map<RandomListNode, RandomListNode> mapper = new HashMap<>(); RandomListNode it = head; while(it != null){ mapper.put(it, new RandomListNode(it.label) ); it = it.next; } it = head; while(it != null){ RandomListNode copy = mapper.get(it); copy.next = mapper.get(it.next); copy.random = mapper.get(it.random); it = it.next; } return mapper.get(head); }}
解题思路2:
1,这里参考网上的方法,直接把copy放在原node的后面,最后再拆链。
总体来看,也是为了 找到 random指向的copy。
2,注意一点,random pointer是可以指向 null的。如果面试官没有说,你也要问。
上面的解法中,hashMap.get(it.random)不用考虑这个问题,因为 hashMap.get(null) 返回还是null
public class Solution { public RandomListNode copyRandomList(RandomListNode head) { if (head == null) return head; RandomListNode it = head; while(it != null){ RandomListNode copy = new RandomListNode(it.label); copy.next = it.next; it.next = copy; it = copy.next; } it = head; while( it != null){ RandomListNode copy = it.next; copy.random = (it.random != null) ? it.random.next : null; it = copy.next; } RandomListNode dummy = new RandomListNode(0); RandomListNode p = dummy; it = head; while( it != null ){ RandomListNode copy=it.next; p.next = copy; it.next = copy.next; it = it.next; p = p.next; } return dummy.next; }}
0 0
- [LeetCode]Copy List with Random Pointer
- [leetcode]Copy List with Random Pointer
- [leetcode][list] Copy List with Random Pointer
- Leetcode: Copy List with Random Pointer
- LeetCode: Copy List with Random Pointer
- [LeetCode] Copy List with Random Pointer
- [leetcode]Copy List with Random Pointer
- LeetCode:Copy List with Random Pointer
- leetcode Copy List with Random Pointer
- LeetCode:Copy List with Random Pointer
- LeetCode题解:Copy List with Random Pointer
- [LeetCode]Copy List with Random Pointer
- leetcode Copy List with Random Pointer
- leetcode-Copy List with Random Pointer
- Leetcode: Copy List with Random Pointer
- LeetCode | Copy List with Random Pointer
- [LeetCode] Copy List with Random Pointer
- LeetCode OJ:Copy List with Random Pointer
- graph slam tutorial :从推导到应用2
- 图表轴刻度的思路,算法: 转载3【求算法:图表控件,如何确定坐标轴的范围和刻度?】
- POJ 1845 Sumdiv (快速幂+质因数+约数和公式+同余模)
- Mac地址加密
- CentOS 7下安装MongoDB
- [leetcode]Copy List with Random Pointer
- ubuntu 安装vmware tools
- 使用教程
- TOYS(计算几何--点与线的关系(叉积+二分(二分之前必须排序!!!)))
- Linux(Ubuntu12)上安装Appium
- HDU 5831(思路题目)
- Android面试准备
- 两个viewport的故事(第二部分)
- hdu1875 畅通工程再续 并查集+kruskal最小生成树