【LeetCode】每日一题——630. 课程表 III

目录

题目:

​ 分析:

 方法:优先队列 + 贪心

参考文章


题目:

 分析:

结束时间越早的课程先排,每次排都紧前排,空闲时间都让给后面。

如果排完一个课程后发现课程总时长超过了最晚的结束时间,说明课程有重叠,删除掉时长最长的课程再继续排。注意这个最长时长课程可能是当前课程

  

 

 方法:优先队列 + 贪心

 

解析看注解 

class Solution:
    def scheduleCourse(self, courses: List[List[int]]) -> int:
        courses.sort(key=lambda c: c[1]) #根据列表中内层列表第一个元素进行排序

        a = list()
        # 优先队列中所有课程的总时间
        total = 0

        for ti, di in courses:
            if total + ti <= di:
                total += ti
                # 内置函数heapq Python 默认是小根堆 变成负数放进去就可以做成大根堆
                heapq.heappush(a, -ti)
            elif a and -a[0] > ti:
                total -= -a[0] - ti #将txj(上图的txj)移除队列
                heapq.heappop(a) # 弹出a的最小 就是t最大
                heapq.heappush(a, -ti)  #将-ti放入a

        return len(a)

 

参考文章

630. 课程表 III【力扣】_xiexie1357的专栏-CSDN博客

Python常用数据结构之heapq模块 - Fate0729 - 博客园

Supongo que te gusta

Origin blog.csdn.net/qq_62932195/article/details/121920603
Recomendado
Clasificación