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 资源

通过相关的交互式教程、备忘单和代码比较来扩展您的知识。