Skip to content

Commit

Permalink
update cheatsheet topology_sorting.md
Browse files Browse the repository at this point in the history
  • Loading branch information
yennanliu committed Nov 9, 2024
1 parent ff574e5 commit 00b80cc
Showing 1 changed file with 71 additions and 0 deletions.
71 changes: 71 additions & 0 deletions doc/cheatsheet/topology_sorting.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
### 0-1) Types
- Courses
- LC 207, LC 210
- Sequence
- LC 444
- Alien Dictionary
- LC 269

Expand Down Expand Up @@ -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<Integer, Set<Integer>> map;
Map<Integer, Integer> indegree;

public boolean sequenceReconstruction_1(int[] nums, List<List<Integer>> sequences) {
map = new HashMap<>();
indegree = new HashMap<>();

for(List<Integer> 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<Integer> 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);
}
}
```

0 comments on commit 00b80cc

Please sign in to comment.