前言
空间换时间是非常常见的降低时间复杂度做法,而hashMap/hash数组/二进制hash就是常用的方式。
一、复制带随机指针的链表
二、hash记录
package everyday.hash;
import java.util.HashMap;
import java.util.Map;
public class CopyRandomList {
public Node copyRandomList(Node head) {
// 设置dummy节点,把特殊情况head==null,以及头节点问题统一处理了。
Node dummyHead = new Node(1);
dummyHead.next = head;
Node cloneDummyHead = new Node(1);
// 记录原始节点和新生成节点映射。
Map<Node, Node> fx = new HashMap<>();
// 设置好头节点与游走节点。
Node p = dummyHead.next;
Node cur = cloneDummyHead.next;
// 设置next
while (p != null) {
// 生成新节点
Node next = new Node(p.val);
// 记录新旧节点映射,为后面设置random指针做准备。
fx.put(p, next);
// 设置新链表next
cur.next = next;
// 更新cur/p
cur = cur.next;
p = p.next;
}
// 设置random
p = dummyHead.next;
cur = cloneDummyHead.next;
while (p != null) {
// 得到cur节点random指向。
Node random = fx.get(p.random);
// 设置random
cur.random = random;
// 更新cur/p
cur = cur.next;
p = p.next;
}
// 返回克隆好的链表
return cloneDummyHead.next;
}
// 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;
}
}
}
总结
1)空间换时间,hashMap/hashSet/hash数组/二进制hash