444. Sequence Reconstruction
題目網址:https://leetcode.cn/problems/sequence-reconstruction/
題意:給一
[1, n]
長度為n
的整數 arraynums
, 以及一些 2d 整數 arraysequences
, 其中sequences[i]
是nums
的 subsequence。返回
sequences
是否能唯一重建出nums
。e.g.
nums = [1,2,3]
,sequences = [[1,2], [1,3]]
sequences
可重建出[1,2,3]
和[1,3,2]
並不唯一, 故返回false
。因為 1 必須在 2、3 的前面, 但 2 和 3 間並沒有唯一的順序- 但若更改
sequences = [[1,2], [1,3], [2,3]]
, 則可唯一重建出[1,2,3]
, 故返回true
。因為 1 必須在 2、3 的前面, 且 2 必須在 3 的前面, 故只能重建出[1,2,3]
Solution:
想法:利用 Topological Sort + BFS, 將
sequences
轉成有向圖, 給定的順序nums
等價於有向圖的 Topological Sort
- 首先, 計算每個點的
inDegree
- 將所有
inDegree = 0
的 node 加到queue
中, 並進行 Topological Sortqueue
中的元素個數表示可以作為下一個數字的元素個數
- 若
queue
中的元素個數> 1
, 則下一個數字並不唯一, 應返回false
- 若
queue
中的元素個數= 1
, 則下一個數字是唯一的數字。並將該數字從queue
取出, 且該數字指向的每個數字的inDegree - 1
, 並將inDegree
變成0
的數字加到queue
中
class Solution { |
- time:$O(n+m)$ ➔
bfs()
所需的時間複雜度 $O(V+E)$n
為nums
的個數(即為 vertex 數)m
為sequences
的個數(即為 edge 數)
- space:$O(n+m)$ ➔ 因為
adj
為 $O(V + E)$,V
是因為要記錄所有點,E
是因為會記錄所有邊
本部落格所有文章除特別聲明外,均採用 CC BY-NC-SA 4.0 許可協議。轉載請註明來自 Zako's Blog!
評論