-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathoffer35.java
More file actions
94 lines (88 loc) · 2.47 KB
/
offer35.java
File metadata and controls
94 lines (88 loc) · 2.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import java.util.HashMap;
/**
* [35] 复杂链表的复制
*
* 题目: 复制含有 next 和 random 指针的复杂链表.
*
* 思路: 1. 维护一个哈希表存储, 原节点和拷贝节点. 然后根据原节点连接各拷贝节点.
* 2. 在每个链表原始节点后创建新节点后, 复制 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 {
/**
* 时间复杂度: O(n)
* 空间复杂度: O(n)
*/
public Node copyRandomList1(Node head) {
if (head == null) {
return null;
}
HashMap<Node, Node> map = new HashMap<>();
Node cur = head;
// clone every node in original list.
while (cur != null) {
map.put(cur, new Node(cur.val));
cur = cur.next;
}
// according to original list to connect clone node.
cur = head;
while (cur != null) {
Node clone = map.get(cur);
clone.next = map.get(cur.next);
clone.random = map.get(cur.random);
cur = cur.next;
}
return map.get(head);
}
/**
* 时间复杂度: O(n)
* 空间复杂度: O(1)
*/
public Node copyRandomList2(Node head) {
if (head == null) {
return null;
}
// put current node's clone node behind current node.
Node cur = head;
while (cur != null) {
Node clone = new Node(cur.val);
clone.next = cur.next;
cur.next = clone;
cur = clone.next;
}
// connect clone's random point.
cur = head;
while (cur != null) {
Node clone = cur.next;
if (cur.random != null) {
// if current node have random point,
// so copy random point.
// clone's random is behind current node's random.
clone.random = cur.random.next;
}
cur = clone.next;
}
// divide long list to before and copy one.
cur = head;
Node cloneHead = cur.next;
// niubility operation(respect).
while (cur.next != null) {
Node next = cur.next;
cur.next = next.next;
cur = next;
}
return cloneHead;
}
}