剑指 Offer II 115. 重建序列

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
class Solution {
public boolean sequenceReconstruction(int[] nums, int[][] sequences) {
Map<Integer, List<Integer>> nodeToNodeListMap = new HashMap<>(); // 边的集合,包含不指向任何节点的单节点,便于统计总节点数
for (int[] sequence : sequences) {
for (int node : sequence) {
nodeToNodeListMap.computeIfAbsent(node, key -> new ArrayList<>());
}
for (int i = 0; i < sequence.length - 1; i++) {
int from = sequence[i], to = sequence[i+1];
nodeToNodeListMap.get(from).add(to);
}
}

if (nums.length > nodeToNodeListMap.size()) {
return false;
}

Map<Integer, Integer> inDegreeMap = new HashMap<>();
for (Map.Entry<Integer, List<Integer>> entry : nodeToNodeListMap.entrySet()) {
int from = entry.getKey();
List<Integer> toList = entry.getValue();
inDegreeMap.putIfAbsent(from, 0);
for (int to : toList) {
inDegreeMap.put(to, inDegreeMap.getOrDefault(to, 0) + 1);
}
}

Queue<Integer> zeroInDegreeNodeQueue = new LinkedList<>();
for (Map.Entry<Integer, Integer> entry : inDegreeMap.entrySet()) {
if (entry.getValue() == 0) {
zeroInDegreeNodeQueue.offer(entry.getKey());
}
}

while (!zeroInDegreeNodeQueue.isEmpty()) {
if (zeroInDegreeNodeQueue.size() > 1) {
return false;
}

int from = zeroInDegreeNodeQueue.poll();
for (int to : nodeToNodeListMap.get(from)) {
int inDegree = inDegreeMap.get(to);
inDegreeMap.put(to, --inDegree);
if (inDegree == 0) {
zeroInDegreeNodeQueue.offer(to);
}
}
}

return true;
}
}

References

剑指 Offer II 115. 重建序列