行业知识
2024.3.6力扣(<=1200)刷题记录-1450. 在既定时间做作业的学生人数
一、题���
1450. 在既定时间做作业的学生人数
二、解题
1.枚举法
class Solution: def busyStudent(self, startTime: List[int], endTime: List[int], queryTime: int) -> int: # 枚举 ans = 0 n = len(startTime) for i in range(n): if startTime[i] int: startTime.sort() endTime.sort() return bisect_right(startTime, queryTime) - bisect_left(endTime, queryTime)
对其中几个我初看时不理解的点罗列出来进行解释:
(1)lessEnd集合包含于lessStart集合
首先lessStart是起始时间小于等于queryTime的学生集合,lessEnd是结束时间小于queryTime的学生集合(注意这里是小于,我们本身需要的是大于等于)。而起始时间小于等于queryTime的学生集合(lessStart集合)包含两种情况:1.结束时间小于queryTime的学生集合(即lessEnd集合);2.结束时间大于等于queryTime的学生集合(即题目需要的集合)。所以lessEnd集合包含于lessStart集合,且从lessStart集合中去掉lessEnd集合中的元素即是满足条件的学生集合。而此处只需要人数,所以只需分别统计两集合个数,相减即可。
(2)代码中的函数
这段代码片段是在使用 Python 的 bisect 模块中的 bisect_right 和 bisect_left 函数来计算符合条件的学生数量。
-
bisect_right(startTime, queryTime):这个函数的作用是找到在排序后的 startTime 数组中,插入 queryTime 所在的位置(即右侧边界)。它返回的是在 startTime 数组中小于等于 queryTime 的元素个数。
-
bisect_left(endTime, queryTime):这个函数的作用是找到在排序后的 endTime 数组中,插入 queryTime 所在的位置(即左侧边界)。它返回的是在 endTime 数组中小于 queryTime 的元素个数。
上段解释来自chatgpt
总而言之,bisect_right(startTime, queryTime)是在startTime中找到大于queryTime的第一个下标(若我们需要的元素个数为num的话,下标指到的位置及之前位置个数是num+1,但是下标还是num),而bisect_left(endTime, queryTime)是找到大于等于queryTime的第一个下标。
下面是我之前看过的一篇关于这个函数的文章的链接:
http://t.csdnimg.cn/vwrhC
感谢你看到这里!一起加油吧!