My Calendar I解题方法
[MyCalendar I 题目描述]
(https://leetcode.com/problems/my-calendar-i/)
当两个事件[a,b)和[c,d)不发生冲突时必须满足b<=c or d<=a;
所以当发生冲突时的情况是c<b and a<d,此时返回false;
否则,添加并返回true;
class MyCalendar {
ArrayList<int[]> calendar = new ArrayList<int[]> ();
MyCalendar() {
}
public boolean book(int start, int end) {
for (int[] i: calendar) {
if (i[0] < end && start < i[1]) return false;
//if(Math.max(i[0],start) < Math.min(i[1],end))
return false;//使用这个if条件作为判断flase的情况也可以
}
calendar.add(new int[]{start, end});
return true;
}
}
My Calendar III解题方法
[MyCalendar III题目描述]
(https://leetcode.com/problems/my-calendar-iii/)
我们建立一个时间点和次数之间的映射,规定遇到起始时间点,次数加1,遇到结束时间点,次数减1。那么我们首先更改新的起始时间start和结束时间end的映射,start对应值增1,end对应值减1。然后定义一个变量cnt,来统计当前的次数。我们使用treemap具有自动排序的功能,所以我们遍历的时候就是按时间顺序的,最先遍历到的一定是一个起始时间,所以加上其映射值,一定是个正数。那么我们想,如果此时只有一个区间,就是刚加进来的区间的话,那么首先肯定遍历到start,那么cnt此时加1,然后就会遍历到end,那么此时cnt减1,最后下来cnt为0,没有重叠。还是用具体数字来说吧,我们现在假设treemap中已经加入了一个区间[3, 5)了,那么我们就有下面的映射:
3 -> 1
5 -> -1
假如我们此时要加入的区间为[6, 8)的话,那么在遍历到6的时候,前面经过3和5,分别加1减1,那么cnt又重置为0了,而后面的6和8也是分别加1减1,还是0。那么加入我们新加入的区间为[3, 8]时,那么此时的映射为:
3 -> 2
5 -> -1
8 -> -1
那么我们最先遍历到3,cnt为2,没有超过3,我们知道此时有两个事件有重叠,是允许的。然后遍历5和8,分别减去1,最终又变成0了,始终cnt没有超过2,所以是符合题意的。如果此时我们再加入一个新的区间[1, 4),那么此时的映射为:
1 -> 1
3 -> 2
4 -> -1
5 -> -1
8 -> -1
相当于每次向数轴中插入一根线段, 每次插入之后返回当前数轴上各个线段之间的最大的重合数。
class MyCalendarThree {
TreeMap<Integer,Integer> t = new TreeMap<Integer,Integer>();
public MyCalendarThree() {
}
public int book(int start, int end) {
t.put(start,t.containsKey(start) ? t.get(start)+1 : 1);
t.put(end,t.containsKey(end) ? t.get(end)-1 : -1);
int res = 0,cur = 0;
for(int i:t.values()){
res = Math.max(res,cur=cur+i);
}
return res;
}
}
/**
* Your MyCalendarThree object will be instantiated and called as such:
* MyCalendarThree obj = new MyCalendarThree();
* int param_1 = obj.book(start,end);
*/