LeetCode 中等题,题目链接:https://leetcode.cn/problems/fu-za-lian-biao-de-fu-zhi-lcof/description/
题目
请实现 copyRandomList
函数,复制一个复杂链表。在复杂链表中,每个节点除了有一个 next
指针指向下一个节点,还有一个 random
指针指向链表中的任意节点或者 null
。
Tips:
Node.random
为空或者指向链表中的节点- 节点数目不超过 1000;
Node
类定义如下:
class Node {
int val;
Node next;
Node random;
public Node(int val) {
this.val = val;
this.next = null;
this.random = null;
}
}
示例1:
输入:head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
输出:[[7,null],[13,0],[11,4],[10,2],[1,0]]
示例2:
输入:head = [[1,1],[2,1]]
输出:[[1,1],[2,1]]
示例3:
输入:head = [[3,null],[3,0],[3,null]]
输出:[[3,null],[3,0],[3,null]]
思路
这道题有两个思路:
- 使用
Map
容器,key
存原链表节点,value
存新节点,原链表的next
节点是Map
中对应的value
节点,原链表的random
节点是Map
中对应的value
节点或者空。 - 拼接 + 拆分,原链表的每个节点下一个指针指向的是新节点(old -> new -> old -> new -> null),新节点的
random
节点是前一个节点的random
节点的下一个节点。
方法一:使用 Map
步骤
- 存新老节点到
Map
中 - 使用
Map
复制节点的next
指针和random
指针
代码
class Solution {
public Node copyRandomList(Node head) {
Map<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 = cur.random == null ? null : map.get(cur.random);
cur = cur.next;
}
return map.get(head);
}
}
复杂度分析
时间复杂度: O ( N ) O(N) O(N)
空间复杂度: O ( N ) O(N) O(N)
方法二:拼接+拆分
- 先遍历一遍,组合出新的链表
- 再次遍历,复制随机值
- 最后一次遍历,拆分链表
代码
class Solution {
public Node copyRandomList(Node head) {
if (head == null) {
return head;
}
// 组合链表
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) {
next = cur.next;
next.random = cur.random == null ? null : cur.random.next;
cur = next.next;
}
// 拆分链表
Node res = head.next;
cur = head;
while (cur != null) {
next = cur.next;
cur.next = next.next;
cur = cur.next;
next.next = cur == null ? null : cur.next;
}
return res;
}
}
复杂度分析
时间复杂度: O ( N ) O(N) O(N)
空间复杂度: O ( 1 ) O(1) O(1)
总结
这是一道 LeetCode 中等题,难点在于如何用更少的空间完成代码,只要思路正确,剩下的就是处理边界条件了。