一、题目
二、解题
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] <= queryTime and queryTime <= endTime[i]:
ans += 1
return ans
看到官方题解(. - 力扣(LeetCode))的枚举法是如下写法:
class Solution:
def busyStudent(self, startTime: List[int], endTime: List[int], queryTime: int) -> int:
# 枚举 生成器
return sum(s <= queryTime <= e for s,e in zip(startTime,endTime))
也就是生成器表达式的写法,和我在《2024.3.5力扣(<=1200)刷题记录1》(http://t.csdnimg.cn/LjJMe)这篇文章里记载的灵神的代码是一个写法,这种写法还需要多多熟悉一下。
2.差分数组法
在官方题解中看到的方法,博主本人不会这个方法,所以去学习了一下。
(学习记录:http://t.csdnimg.cn/MzohU)
根据官方题解,参考学习后,写出如下代码:
class Solution:
def busyStudent(self, startTime: List[int], endTime: List[int], queryTime: int) -> int:
# 差分数组
maxTime = max(endTime) #最大的时间决定差分数组的大小
if queryTime > maxTime: #不然可能会超出范围
return 0
cnt = [0] * (maxTime + 2) #差分数组,加一舍弃下标为0的位,再加一避免越界
for i in range(len(startTime)):
cnt[startTime[i]] += 1
cnt[endTime[i]+1] -= 1
return sum(cnt[:queryTime+1]) #前缀和,0位为0不影响和
3.二分查找法
也是在官方题解中看到的方法,也来学习一下。官方题解是这样说明的:
代码如下:
class Solution:
def busyStudent(self, startTime: List[int], endTime: List[int], queryTime: int) -> 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
的第一个下标。
下面是我之前看过的一篇关于这个函数的文章的链接:
感谢你看到这里!一起加油吧!