|
11 | 11 | ### 0-1) Types |
12 | 12 | - Courses |
13 | 13 | - LC 207, LC 210 |
| 14 | +- Sequence |
| 15 | + - LC 444 |
14 | 16 | - Alien Dictionary |
15 | 17 | - LC 269 |
16 | 18 |
|
@@ -503,4 +505,73 @@ class Solution(object): |
503 | 505 | in_degree[word2[i]].add(word1[i]) |
504 | 506 | out_degree[word1[i]].add(word2[i]) |
505 | 507 | break |
| 508 | +``` |
| 509 | + |
| 510 | +### 2-3) Sequence Reconstruction |
| 511 | + |
| 512 | +```java |
| 513 | +// java |
| 514 | +// LC 444 |
| 515 | + // V1 |
| 516 | + // https://www.youtube.com/watch?v=FHY1q1h9gq0 |
| 517 | + // https://www.jiakaobo.com/leetcode/444.%20Sequence%20Reconstruction.html |
| 518 | + Map<Integer, Set<Integer>> map; |
| 519 | + Map<Integer, Integer> indegree; |
| 520 | + |
| 521 | + public boolean sequenceReconstruction_1(int[] nums, List<List<Integer>> sequences) { |
| 522 | + map = new HashMap<>(); |
| 523 | + indegree = new HashMap<>(); |
| 524 | + |
| 525 | + for(List<Integer> seq: sequences) { |
| 526 | + if(seq.size() == 1) { |
| 527 | + addNode(seq.get(0)); |
| 528 | + } else { |
| 529 | + for(int i = 0; i < seq.size() - 1; i++) { |
| 530 | + addNode(seq.get(i)); |
| 531 | + addNode(seq.get(i + 1)); |
| 532 | + |
| 533 | + // 加入子节点, 子节点增加一个入度 |
| 534 | + // [1,2] => 1 -> 2 |
| 535 | + // 1: [2] |
| 536 | + int curr = seq.get(i); |
| 537 | + int next = seq.get(i + 1); |
| 538 | + if(map.get(curr).add(next)) { |
| 539 | + indegree.put(next, indegree.get(next) + 1); |
| 540 | + } |
| 541 | + } |
| 542 | + } |
| 543 | + } |
| 544 | + |
| 545 | + Queue<Integer> queue = new LinkedList<>(); |
| 546 | + for(int key : indegree.keySet()) { |
| 547 | + if(indegree.get(key) == 0){ |
| 548 | + queue.offer(key); |
| 549 | + } |
| 550 | + } |
| 551 | + |
| 552 | + int index = 0; |
| 553 | + while(!queue.isEmpty()) { |
| 554 | + // 如果只有唯一解, 那么queue的大小永远都是1 |
| 555 | + if(queue.size() != 1) return false; |
| 556 | + |
| 557 | + int curr = queue.poll(); |
| 558 | + if(curr != nums[index++]) return false; |
| 559 | + |
| 560 | + for(int next: map.get(curr)) { |
| 561 | + indegree.put(next, indegree.get(next) - 1); |
| 562 | + if(indegree.get(next) == 0) { |
| 563 | + queue.offer(next); |
| 564 | + } |
| 565 | + } |
| 566 | + } |
| 567 | + |
| 568 | + return index == nums.length; |
| 569 | + } |
| 570 | + |
| 571 | + private void addNode(int node) { |
| 572 | + if(!map.containsKey(node)) { |
| 573 | + map.put(node, new HashSet<>()); |
| 574 | + indegree.put(node, 0); |
| 575 | + } |
| 576 | + } |
506 | 577 | ``` |
0 commit comments