diff --git a/doc/cheatsheet/topology_sorting.md b/doc/cheatsheet/topology_sorting.md index 04b39196..773ff265 100644 --- a/doc/cheatsheet/topology_sorting.md +++ b/doc/cheatsheet/topology_sorting.md @@ -11,6 +11,8 @@ ### 0-1) Types - Courses - LC 207, LC 210 +- Sequence + - LC 444 - Alien Dictionary - LC 269 @@ -503,4 +505,73 @@ class Solution(object): in_degree[word2[i]].add(word1[i]) out_degree[word1[i]].add(word2[i]) break   +``` + +### 2-3) Sequence Reconstruction + +```java +// java +// LC 444 + // V1 + // https://www.youtube.com/watch?v=FHY1q1h9gq0 + // https://www.jiakaobo.com/leetcode/444.%20Sequence%20Reconstruction.html + Map> map; + Map indegree; + + public boolean sequenceReconstruction_1(int[] nums, List> sequences) { + map = new HashMap<>(); + indegree = new HashMap<>(); + + for(List seq: sequences) { + if(seq.size() == 1) { + addNode(seq.get(0)); + } else { + for(int i = 0; i < seq.size() - 1; i++) { + addNode(seq.get(i)); + addNode(seq.get(i + 1)); + + // 加入子节点, 子节点增加一个入度 + // [1,2] => 1 -> 2 + // 1: [2] + int curr = seq.get(i); + int next = seq.get(i + 1); + if(map.get(curr).add(next)) { + indegree.put(next, indegree.get(next) + 1); + } + } + } + } + + Queue queue = new LinkedList<>(); + for(int key : indegree.keySet()) { + if(indegree.get(key) == 0){ + queue.offer(key); + } + } + + int index = 0; + while(!queue.isEmpty()) { + // 如果只有唯一解, 那么queue的大小永远都是1 + if(queue.size() != 1) return false; + + int curr = queue.poll(); + if(curr != nums[index++]) return false; + + for(int next: map.get(curr)) { + indegree.put(next, indegree.get(next) - 1); + if(indegree.get(next) == 0) { + queue.offer(next); + } + } + } + + return index == nums.length; + } + + private void addNode(int node) { + if(!map.containsKey(node)) { + map.put(node, new HashSet<>()); + indegree.put(node, 0); + } + } ``` \ No newline at end of file