【
实现一个 MyCalendar 类来存放你的日程安排。如果要添加的时间内不会导致三重预订时,则可以存储这个新的日程安排。
MyCalendar 有一个 book(int start, int end)方法。它意味着在 start 到 end 时间内增加一个日程安排,注意,这里的时间是半开区间,即 [start, end), 实数 x 的范围为, start <= x < end。
当三个日程安排有一些时间上的交叉时(例如三个日程安排都在同一时间内),就会产生三重预订。
每次调用 MyCalendar.book方法时,如果可以将日程安排成功添加到日历中而不会导致三重预订,返回 true。否则,返回 false 并且不要将该日程安排添加到日历中。
请按照以下步骤调用MyCalendar 类: MyCalendar cal = new MyCalendar(); MyCalendar.book(start, end)
示例:
MyCalendar();
MyCalendar.book(10, 20); // returns true
MyCalendar.book(50, 60); // returns true
MyCalendar.book(10, 40); // returns true
MyCalendar.book(5, 15); // returns false
MyCalendar.book(5, 10); // returns true
MyCalendar.book(25, 55); // returns true
解释:
前两个日程安排可以添加至日历中。 第三个日程安排会导致双重预订,但可以添加至日历中。
第四个日程安排活动(5,15)不能添加至日历中,因为它会导致三重预订。
第五个日程安排(5,10)可以添加至日历中,因为它未使用已经双重预订的时间10。
第六个日程安排(25,55)可以添加至日历中,因为时间 [25,40] 将和第三个日程安排双重预订;
时间 [40,50] 将单独预订,时间 [50,55)将和第二个日程安排双重预订。
提示:
每个测试用例,调用 MyCalendar.book 函数最多不超过 1000次。
调用函数 MyCalendar.book(start, end)时, start 和 end 的取值范围为 [0, 10^9]。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/my-calendar-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
】
相比较于729题,731是其升级版,判断三重预定。
类似思路,分别用两组数组分别存放可以预定的起始和一次冲突的预定。
注意一次冲突的数组中,我们不关系是否有重复元素,反正最多1000次。
同时无论有没冲突,我们都把可以的预定存入数组。
代码如下:
- typedef struct {
- int flarr[1000];
- int frarr[1000];
- int slarr[1000];
- int srarr[1000];
- } MyCalendarTwo;
-
- int fidx;
- int sidx;
-
- MyCalendarTwo* myCalendarTwoCreate() {
- MyCalendarTwo *obj = (MyCalendarTwo *)malloc(sizeof(MyCalendarTwo));
- fidx = 0;
- sidx = 0;
-
- return obj;
- }
-
- bool myCalendarTwoBook(MyCalendarTwo* obj, int start, int end) {
- int i;
-
- for (i = 0; i < sidx; i++) { // 和二重预定数组比较
- if (start < obj->srarr[i] && end > obj->slarr[i]) { // 这种肯定就冲突了
- return false;
- }
- }
-
- // 新增的二重预定可能和以前二重预定一样,但还是直接加进去,重复就重复
- for (i = 0; i < fidx; i++) {
- if (start < obj->frarr[i] && end > obj->flarr[i]) { // 有冲突,放入二重预定数组里面
- obj->slarr[sidx] = fmax(start, obj->flarr[i]); // 注意边界处理
- obj->srarr[sidx] = fmin(end, obj->frarr[i]);
- sidx++;
- }
- }
-
- // 放入一重预定数组里,无论有没有冲突
- obj->flarr[fidx] = start;
- obj->frarr[fidx] = end;
- fidx++;
-
- return true;
- }
-
- void myCalendarTwoFree(MyCalendarTwo* obj) {
- free(obj);
- }
-
- /**
- * Your MyCalendarTwo struct will be instantiated and called as such:
- * MyCalendarTwo* obj = myCalendarTwoCreate();
- * bool param_1 = myCalendarTwoBook(obj, start, end);
-
- * myCalendarTwoFree(obj);
- */