题目
解法一:哈希
遍历两遍,第一遍创建节点,处理next,第二遍处理 random
/*
// 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) {
Set<Node> oldLinkList = new HashSet<>();
Map<Node, Node> newLinkList = new HashMap<>();
Node dummyHead = new Node(-1), p = dummyHead, p1 = head;
while (p1 != null) {
Node newNode = new Node(p1.val);
p.next = newNode;
p = p.next;
oldLinkList.add(p1);
newLinkList.put(p1, newNode);
if (p1.random == null) {
newNode.random = null;
}
p1 = p1.next;
}
p.next = null;
p = dummyHead.next;
p1 = head;
while (p1 != null && p != null) {
if (p1.random != null && oldLinkList.contains(p1.random))
p.random = newLinkList.get(p1.random);
p = p.next;
p1 = p1.next;
}
return dummyHead.next;
}
}
- 时间复杂度:O(n)
- 空间复杂度:O(n)
解法一的优化:哈希
class Solution {
public Node copyRandomList(Node head) {
if (head == null) return null;
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 = map.get(cur.random);
cur = cur.next;
}
return map.get(head);
}
}
- 时间复杂度:O(n)
- 空间复杂度:O(n)
解法二:迭代 + 节点拆分
class Solution {
public Node copyRandomList(Node head) {
if (head == null) return null;
// 1 -> copy1 -> 2 -> copy2...
for (Node node = head; node != null; node = node.next.next) {
Node newNode = new Node(node.val);
newNode.next = node.next;
node.next = newNode;
}
for (Node node = head; node != null; node = node.next.next) {
Node newNode = node.next;
newNode.random = (node.random == null) ? null : node.random.next;
}
// 拆链
Node newHead = head.next;
for (Node node = head; node != null; node = node.next) {
Node newNode = node.next;
node.next = node.next.next;
newNode.next = (newNode.next != null) ? newNode.next.next : null;
}
return newHead;
}
}
- 时间复杂度:O(n)
- 空间复杂度:O(1)
解法三:递归(回溯+哈希表)
class Solution {
Map<Node, Node> cachedNode = new HashMap<Node, Node>();
public Node copyRandomList(Node head) {
if (head == null) {
return null;
}
if (!cachedNode.containsKey(head)) {
Node headNew = new Node(head.val);
cachedNode.put(head, headNew);
headNew.next = copyRandomList(head.next);
headNew.random = copyRandomList(head.random);
}
return cachedNode.get(head);
}
}
作者:力扣官方题解
链接:https://leetcode.cn/problems/copy-list-with-random-pointer/solutions/889166/fu-zhi-dai-sui-ji-zhi-zhen-de-lian-biao-rblsf/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
- 时间复杂度:O(n)
- 空间复杂度:O(n)