150強訪談簡單

課程安排二

「課程表 II」問題的詳細指南和 Python 實作。

問題陳述

簡單

您必須選修 numCourses 課程,標記為從 0 到 numCourses - 1。您將獲得一個陣列先決條件,其中先決條件 [i] = [ai, bi] 表示如果您想選修課程 ai,則必須先選修課程 bi。

返回完成所有課程所需的課程順序。如果有很多有效答案,則傳回其中任何一個。如果不可能完成所有課程,則傳回一個空數組。

寫一個函數 findOrder(numCourses: int, prerequisites: List[List[int]]) -> List[int]

約束條件
  • 1 <= numCourses <= 2000
  • 0 <= len(prerequisites) <= 5000
  • prerequisites[i].length == 2
  • 0 <= ai, bi < numCourses

範例

Example 1
Input
numCourses = 2, prerequisites = [[1,0]]
Output
[0,1]
Explanation

There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is [0,1].

Example 2
Input
numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]]
Output
[0,2,1,3]
Explanation

There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. So one correct course order is [0,1,2,3]. Another correct ordering is [0,2,1,3].

Need a Hint?
考慮使用特定於圖的資料結構,例如集合或堆。
Edge Cases to Watch
  • 空輸入結構
  • 單元素輸入
  • 大數值範圍

準備好解決了嗎?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在編輯器中開啟
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推薦的 Python 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。