2020-6-3
题目链接
题目描述:
给定一个链表,每个节点包含一个额外增加的随机指针,该指针可以指向链表中的任何节点或空节点。 要求返回这个链表的 深拷贝。 我们用一个由 n 个节点组成的链表来表示输入/输出中的链表。每个节点用一个 [val, random_index] 表示: val:一个表示 Node.val 的整数。 random_index:随机指针指向的节点索引(范围从 0 到 n-1);如果不指向任何节点,则为 null 。
思路一:Hash
使用hash表这种数据结构。hash-key存储原链表的节点,hash-value则对应存储复制的节点。通过key-value的对应关系,可以推断:node'.next = map.get(node.next);
且有:node'.rand = map.get(node.rand);
代码如下:
/* // 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) { HashMap<Node,Node> map = new HashMap<>(); Node cur = head; while(cur != null){ map.put(cur,new Node(cur.val)); cur = cur.next; } cur = head; while(cur != null){ map.get(cur).next = map.get(cur.next); map.get(cur).random = map.get(cur.random); cur = cur.next; } return map.get(head); } }
时间复杂度:O(N)
额外空间复杂度:O(N)
代码执行结果:
思路二:指针思路,不使用额外的数据空间
现有带有rand指针的链表如下,橙色为rand,蓝色为next:
先不考虑rand指针,我们将链表复制成如下结构,红色node为复制的部分:
当形成这种结构的链表时,其实也就等同于hash表了。不难看出,复制的节点的next指针与rand指针应该如何指向,代码如下:
/* // 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) { if(head == null){ return null; } Node cur = head; Node next = null; while(cur != null){ next = cur.next; cur.next = new Node(cur.val); cur.next.next = next; cur = next; } cur = head; while(cur != null){ cur.next.random = cur.random == null ? null : cur.random.next; cur = cur.next.next; } cur = head; Node res = head.next; Node curCopy = null; while(cur != null){ next = cur.next.next; curCopy = cur.next; cur.next = next; curCopy.next = curCopy.next == null ? null : curCopy.next.next; cur = next; } return res; } }
时间复杂度:O(N)
额外空间复杂度:O(1)
代码执行结果: