207. Course Schedule

https://leetcode.com/problems/course-schedule/

solution

  • 建图,判断图是否有环

  • 标准的拓扑排序写法

class Solution:
    def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
        graph = collections.defaultdict(list)
        degree = [0] * numCourses  # 也可以使用collections.defaultdict(int)

        for (cur, pre) in prerequisites:
            graph[pre].append(cur)  # bfs往后走所以记录后面
            degree[cur] += 1  # 后面是否可开始依赖前面

        start_course = [i for (i, d) in enumerate(degree) if d == 0]
        queue = collections.deque(start_course)
        visited = 0
        while queue:
            cur = queue.popleft()
            visited += 1
            for adj in graph[cur]:  # graph记录后续可以开始的课程
                degree[adj] -= 1  # 后续课程的前依赖 - 1
                if not degree[adj]:
                    queue.append(adj)
        return visited == numCourses
  • 建立队列存储不需要先行课程的课程,从队列中取出元素,找到依赖该元素的后续课程。如果后续课程不再依赖其他课程,则加入队列

时间复杂度:O(E+V) 空间复杂度:O(E+V)

Follow-up

调度类

210. Course Schedule II

630 Course Schedule III

1462 Course Schedule IV

1834 Single-Threaded CPU

  • dijkstra: 用heap

  • 超时: 用heap 代替BFS的deque

621 Task Scheduler

2365 Task Scheduler II

1029 Two City Scheduling

*1229 Meeting Scheduler

  • 双指针

1335 Minimum Difficulty of a Job Schedule

1235 Maximum Profit in Job Scheduling

2050. Parallel Courses III

*2402. Meeting Rooms III

1882. Process Tasks Using Servers

  • two heap 思路比较巧妙: 一个存储正在工作的server, 一个存储空闲的server

  • straight [需要debug, 没有全过]

1386. Cinema Seat Allocation

Task scheduler

  • multiple ec2 machine 处理 task,每个machine 能同时处理10个jobs,then we want to have an algorithm that when can we start for the next job

拓扑排序类

*261. Graph Valid Tree

  • union find

*269 Alien Dictionary

Last updated