Problem
LeetCode 138. Copy List with Random Pointer
1. 题目简述
给定一个链表,每个节点包含一个额外增加的随机指针,该指针可以指向链表中的任何节点或空节点。
要求返回这个链表的 深拷贝。
我们用一个由 n 个节点组成的链表来表示输入/输出中的链表。每个节点用一个 [val, random_index] 表示:
val:一个表示 Node.val 的整数。
random_index:随机指针指向的节点索引(范围从 0 到 n-1);如果不指向任何节点,则为 null 。
Examples:
输入:head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
输出:[[7,null],[13,0],[11,4],[10,2],[1,0]]
2. 算法思路
哈希表(要绕个弯)
首先,这道题的难点在于那个random指针,我们根本无从知晓这个random究竟会指向哪个节点,究竟是已经被我们创建还是未被我们创建。而且每个节点的value值与自己的index顺序也不是对应的,所以不能用传统的数组寻址的方式,而是hashmap。
对于每个节点,我们用原始的node作为key,新建的node作为value,这样,我们只需要先从前向后遍历一次创建所有节点,再从前向后将所有的next和random指向对应节点即可。
O(1)空间复杂度的方法
可以对原链表进行修改,解法见:传送门
3. 解法
HashMap:
/*
// Definition for a Node.
class Node {
int val;
Node next;
Node random;
public Node(int val) {
this.val = val;
this.next = null;
this.random = null;
}
}
*/
class Solution {
public Node copyRandomList(Node head) {
Map<Node, Node> clone = new HashMap();
Node ptr = head;
// create all nodes
while (ptr != null) {
clone.put(ptr, new Node(ptr.val));
ptr = ptr.next;
}
// make the next and random pointer to the pright place
ptr = head;
while (ptr != null) {
Node node = clone.get(ptr);
node.next = clone.get(ptr.next);
node.random = clone.get(ptr.random);
ptr = ptr.next;
}
return clone.get(head);
}
}