#Problem

#⭐️⭐️⭐️

My Calendar I

#Solution

用一个tree set根据start time排序. 然后对于每一个add请求, 找floor和ceiling的interval, 看是否有重合.

#Code

#Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class MyCalendar {
private TreeSet<int[]> treeSet;
public MyCalendar() {
this.treeSet = new TreeSet<>((a, b) -> { return a[0] - b[0]; });
}
public boolean book(int start, int end) {
int[] curr = new int[] {start, end};
if (!treeSet.isEmpty()) {
int[] floor = treeSet.floor(curr);
int[] ceiling = treeSet.ceiling(curr);
if (floor != null && floor[1] > curr[0]) return false;
if (ceiling != null && ceiling[0] < curr[1]) return false;
}
treeSet.add(curr);
return true;
}
}

Comments