A k-booking happens when k events have some non-empty intersection (i.e., there is some time that is common to all k events.)
You are given some events [start, end), after each given event, return an integer k representing the maximum k-booking between all the previous events.
Implement the MyCalendarThree class:
MyCalendarThree() Initializes the object.
int book(int start, int end) Returns an integer k representing the largest integer such that there exists a k-booking in the calendar.
Example 1:
Input
[“MyCalendarThree”, “book”, “book”, “book”, “book”, “book”, “book”]
[[], [10, 20], [50, 60], [10, 40], [5, 15], [5, 10], [25, 55]]
Output
[null, 1, 1, 2, 3, 3, 3]
Explanation
MyCalendarThree myCalendarThree = new MyCalendarThree();
myCalendarThree.book(10, 20); // return 1, The first event can be booked and is disjoint, so the maximum k-booking is a 1-booking.
myCalendarThree.book(50, 60); // return 1, The second event can be booked and is disjoint, so the maximum k-booking is a 1-booking.
myCalendarThree.book(10, 40); // return 2, The third event [10, 40) intersects the first event, and the maximum k-booking is a 2-booking.
myCalendarThree.book(5, 15); // return 3, The remaining events cause the maximum K-booking to be only a 3-booking.
myCalendarThree.book(5, 10); // return 3
myCalendarThree.book(25, 55); // return 3
Constraints:
- 0 <= start < end <= 109
- At most 400 calls will be made to book.
我们将整个区间 0-1000000000 构建一个 segment tree, 按顺序每次取出一对[start, end], 会有如下三种情况:
- 如果 end 小于当前节点的 left 或者 start 大于当前节点的 right, 即[start, end]与当前节点的区间没有交集, 则不对当前节点的公共时间点造成影响。
- 如果 start <= 当前节点的 left 并且当前节点的 right <= end, 即[start, end]完全覆盖当前的节点区间, 当前节点的公共时间点计数+1
- 如果部分覆盖, 则递归更新左侧子节点和右侧子节点的计数, 当前节点的公共时间点计数= 情况 2 全覆盖的计数+max(左侧子节点的公共时间点计数, 右侧子节点的公共时间点计数)。
这里面有两个比较棘手的地方, 一个是,全覆盖计数和全部计数的关系,另一个是开闭区间的覆盖判断。leetcode 自己对这题的解析其实很不错,大家还是看原文吧
use std::collections::HashMap;
struct MyCalendarThree {
vals: HashMap<i32, i32>,
lazy: HashMap<i32, i32>,
}
/**
* `&self` means the method takes an immutable reference.
* If you need a mutable reference, change it to `&mut self` instead.
*/
impl MyCalendarThree {
fn new() -> Self {
Self {
vals: HashMap::new(),
lazy: HashMap::new(),
}
}
fn update(&mut self, start: i32, end: i32, left: i32, right: i32, idx: i32) {
if start > right || end < left {
return;
}
if start <= left && right <= end {
*self.vals.entry(idx).or_insert(0) += 1;
*self.lazy.entry(idx).or_insert(0) += 1;
return;
}
let mid = (left + right) / 2;
self.update(start, end, left, mid, idx * 2);
self.update(start, end, mid + 1, right, idx * 2 + 1);
self.vals.insert(
idx,
*self.lazy.get(&idx).unwrap_or(&0)
+ (*self.vals.get(&(idx * 2)).unwrap_or(&0))
.max(*self.vals.get(&(idx * 2 + 1)).unwrap_or(&0)),
);
}
fn book(&mut self, start: i32, end: i32) -> i32 {
self.update(start, end - 1, 0, 10i32.pow(9), 1);
*self.vals.get(&1).unwrap_or(&0)
}
}