150强访谈简单

课程安排

“课程表”问题的详细指南和 Python 实现。

问题陈述

简单

您必须选修 numCourses 课程,标记为从 0 到 numCourses - 1。您将获得一个数组先决条件,其中先决条件 [i] = [ai, bi] 表示如果您想选修课程 ai,则必须先选修课程 bi。

例如,[0, 1] 对表示要学习课程 0,您必须先学习课程 1。

如果您可以完成所有课程,则返回 True。否则,返回 False。

编写一个函数 canFinish(numCourses: int, prerequisites: List[List[int]]) -> bool

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

示例

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

To take course 1 you should have finished course 0. So it is possible.

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

To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. This is a cycle and therefore impossible.

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

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