LeetCode題解(0210):課程表II(Python)
題目:原題連結(中等)
標籤:圖、拓撲排序、廣度優先搜尋、深度優先搜尋
解法 | 時間複雜度 | 空間複雜度 | 執行用時 |
---|---|---|---|
Ans 1 (Python) | O ( N ) O(N) O(N) | O ( N ) O(N) O(N) | 84ms (12.88%) |
Ans 2 (Python) | |||
Ans 3 (Python) |
解法一:
def build_graph(edges):
graph_in = collections.defaultdict(set)
graph_out = collections.defaultdict(set)
for edge in edges:
graph_in[edge[1]].add(edge[0])
graph_out[edge[0]].add(edge[1])
return graph_out, graph_in
def topo(graph_in, graph_out):
count = {} # 節點入射邊統計
queue = [] # 當前入射邊為0的節點列表
# 統計所有節點的入射邊
for node in graph_in:
count[node] = len(graph_in[node])
for node in graph_out:
if node not in count:
count[node] = 0
queue.append(node)
# 拓撲排序
order = []
while queue:
node = queue.pop()
order.append(node)
for next in graph_out[node]:
count[next] -= 1
if count[next] == 0:
queue.append(next)
return order
class Solution:
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
# 生成有向圖中邊的鄰接列表結構
graph_in, graph_out = build_graph(prerequisites)
# 拓撲排序
order = topo(graph_in, graph_out)
order_set = set(order)
for node in graph_in:
if node not in order:
return []
for i in range(numCourses):
if i not in order_set:
order.append(i)
return order
相關文章
- LeetCode題解(0407):接雨水II(Python)LeetCodePython
- LeetCode 207. 課程表(Medium)LeetCode
- LeetCode 272 Closest Binary Tree Traversal II 解題思路LeetCode
- leetcode題解(查詢表問題)LeetCode
- 【LeetCode】253. Meeting Rooms II 解題報告(C++)LeetCodeOOMC++
- 0210
- 207. 課程表
- 【leetcode】每日精選題詳解之59. 螺旋矩陣 IILeetCode矩陣
- 力扣刷題筆記:207. 課程表力扣筆記
- LeetCode 59. 螺旋矩陣 II(python、c++)LeetCode矩陣PythonC++
- leetcode 831題解【C++/Java/Python】LeetCodeC++JavaPython
- LeetCode題解(1652):拆炸彈(Python)LeetCodePython
- LeetCode題解(1178):猜字謎(Python)LeetCodePython
- Python開發系列課程彙總 - 課程大綱Python
- leetcode 解題 2.兩數相加-python3 題解LeetCodePython
- python是什麼課程Python
- Python的容器有哪些?Python課程Python
- 學校課程表爬取
- Leetcode每日一題:52.N-Queens II(N皇后Ⅱ)LeetCode每日一題
- 必看,經典sql面試題2(學生表_課程表_成績表_教師表)SQL面試題
- 必看,經典sql面試題1(學生表_課程表_成績表_教師表)SQL面試題
- 每日一道演算法題--leetcode 113--路徑總和II--python演算法LeetCodePython
- leetcode-90. Subsets IILeetCode
- Leetcode 40 Combination Sum IILeetCode
- Leetcode 213 House Robber IILeetCode
- LeetCode 1103[分糖果II]LeetCode
- LeetCode題解:264. 醜數 II,二叉堆,JavaScript,詳細註釋LeetCodeJavaScript
- LeetCode每日一題--621. 任務排程器(雜湊表)LeetCode每日一題
- LeetCode題解(1668):最大重複子字串(Python)LeetCode字串Python
- PYTHON openpyxl 讀取課程表,輪值排班表,輸出每日班級簡報Python
- leetcode 題解:python3@ 官方題解_暴力法_雙指標法LeetCodePython指標
- python暑期課程 day1Python
- Python課程程式碼實現Python
- LeetCode每日一題: 按奇偶排序陣列 II(No.27)LeetCode每日一題排序陣列
- 3.25 建立報名表和課程表
- CSDN學院:24門精品課程免費領取(含Python+人工智慧等專題課程)Python人工智慧
- [LeetCode] 210. Course Schedule IILeetCode
- [LeetCode] 305. Number of Islands IILeetCode