Description:
Implement a MyCalendarThree class to store your events. A new event can always be added.
Your class will have one method, book(int start, int end). Formally, this represents a booking on the half open interval [start, end), the range of real numbers x such that start <= x < end.
A K-booking happens when K events have some non-empty intersection (ie., there is some time that is common to all K events.)
For each call to the method MyCalendar.book, return an integer K representing the largest integer such that there exists a K-booking in the calendar.
Your class will be called like this: MyCalendarThree cal = new MyCalendarThree(); MyCalendarThree.book(start, end)
Example 1:
MyCalendarThree();
MyCalendarThree.book(10, 20); // returns 1
MyCalendarThree.book(50, 60); // returns 1
MyCalendarThree.book(10, 40); // returns 2
MyCalendarThree.book(5, 15); // returns 3
MyCalendarThree.book(5, 10); // returns 3
MyCalendarThree.book(25, 55); // returns 3
Explanation:
The first two events can be booked and are disjoint, so the maximum K-booking is a 1-booking.
The third event [10, 40) intersects the first event, and the maximum K-booking is a 2-booking.
The remaining events cause the maximum K-booking to be only a 3-booking.
Note that the last event locally causes a 2-booking, but the answer is still 3 because
eg. [10, 20), [10, 40), and [5, 15) are still triple booked.
解题思路:
book分别记录start和end,在start处+1(代表新事件开始),在end处-1(代表事件结束),然后有序遍历,累加求和,找出遍历过程中累加的最大值。
解法1,使用TreeMap:
class MyCalendarThree {
TreeMap<Integer, Integer> delta;
public MyCalendarThree() {
delta = new TreeMap();
}
public int book(int start, int end) {
delta.put(start, delta.getOrDefault(start, 0) + 1);
delta.put(end, delta.getOrDefault(end, 0) - 1);
int active = 0, ans = 0;
for (int d: delta.values()) {
active += d;
if (active > ans) ans = active;
}
return ans;
}
}
解法2,二分查找树:
class MyCalendarThree {
class Node{
private int k, v;
private Node left, right;
public Node(int k, int v) {
this.k = k;
this.v = v;
}
}
private Node root;
private int curt, count;
public MyCalendarThree() {
}
private Node insert(Node node, int k, int v) {
if (node == null) {
node = new Node(k, v);
return node;
} else if (node.k == k) {
node.v += v;
} else if (node.k < k) {
node.right = insert(node.right, k, v);
} else {
node.left = insert(node.left, k, v);
}
return node;
}
private void count(Node node) {
if (node == null) {
return;
}
count(node.left);
curt += node.v;
count = Math.max(count, curt);
count(node.right);
}
public int book(int start, int end) {
root = insert(root, start, 1);
root = insert(root, end, -1);
curt = count = 0;
count(root);
return count;
}
}
注意,二分查找树的中序遍历正好对应的事件时间的有序序列