QUESTION:
My Think:
Today we are talking about MyCalendar I II III. The daily questions for these three days are the same, so we will do them together.
今天我们讲MyCalendar I II III, 这三天的每日一题都是一样的,所以一起做了.
I:
We use binary search to find where startTime
can be inserted, and return False
if it is found in advance. After finding the insertion point, we can check whether there is overlap.
我们用二分查找, 查找 startTime
在哪里可以插入, 如果提前找到了直接返回 False
. 找到了插入点后, 再检查是否有重叠即可.
1 | class MyCalendar: |
II:
This question requires us to check whether there will be three reservations under the conditions of the previous question. Although binary search can also be done, it will be much more complicated. We introduce the idea of differential (Line Sweep) in this question.
Record the changes at each time point (start and end)
When a new interval[startTime, endTime)
is to be inserted:- At the position corresponding to
startTime
+1 - At the position corresponding to
endTime
-1
In this way, we only record “how much the overlap number should be added/subtracted at these two boundary time points”.
- At the position corresponding to
Count the current maximum overlap when necessary
Sort all-time points (keys) from small to large, and accumulate their +1/-1 values in turn.
The result of the accumulation is the number of activities carried out simultaneously at the corresponding time (that is, the “overlap number”).
If you want to find out whether there is a triple reservation, see whether the maximum of this accumulation process reaches 3 (or higher)
这道题要求我们在上一道题的条件下, 检查是否会出现三次预定. 二分查找虽然也可以做, 但是会复杂很多. 我们在这一题引入差分(Line Sweep)的思想.
记录每个时间点(开始与结束)的变化
当有新的区间[startTime, endTime)
要插入时:- 在
startTime
对应的位置 +1 - 在
endTime
对应的位置 -1
这样我们只记录“在这两个边界时间点,重叠数量要加/减多少”。
- 在
在需要时统计当前的最大重叠
把所有的时间点(key)从小到大排序,依次累加其 +1/-1 值。
累加的结果就是对应时刻同时进行的活动数量(也就是“重叠数量”)。
如果要查找是否出现三重预定,就看这个累加过程最大是否到达 3(或更高)
1 | from sortedcontainers import SortedDict |
III:
This question is even more difficult. It requires us to find the maximum number of multiple reservations. We can just record it based on the previous question.
Difference record
Same as before:
+1
at the position corresponding tostartTime
,-1
at the position corresponding toendTime
.Store in
self.sd
:key
= time point,value
= increase or decrease at that time point.Find the maximum number of overlaps
Use a rolling variable ongoing to indicate “how many overlaps there are at the current moment”.
Each time a time point is traversed, the corresponding difference is accumulated to ongoing, and thenmax_overlap = max(max_overlap, ongoing)
is updated.
这道题更加过分, 要求我们找到多重预定中最多有多少重, 我们就在上一道题的基础上记录即可.
差分记录
与之前一致:在
startTime
对应的位置 +1
,在endTime
对应的位置-1
。
self.sd
中存储:key=时间点,value
=该时间点的增减量。求最大重叠数
用一个滚动变量
ongoing
表示“当前时刻有多少重叠”。
每遍历一个时间点,把对应的差分累加到ongoing
,然后更新max_overlap = max(max_overlap, ongoing)
。
1 | from sortedcontainers import SortedDict |