题目来源:https://leetcode.cn/problems/my-calendar-iii/
大致题意:
设计一个类存放日程安排,需要实现以下方法:
- int book(int start, int end) 在给定时间范围 [start, end] 内添加一个日程,返回一个整数 k ,当前日历中某一时刻重复安排的日程数量的最大值
思路
使用差分思想,在给定时间范围 [start, end] 内添加一个日程,相当于:
- 在差分数组 nums[start]++,nums[end + 1]–
那么,最大值即为当前差分数组所有前缀和的最大值
因为本题使用数据值较大且数据分布较为离散,直接使用数组实现差分会超时,所以选择使用有序集合(TreeMap)实现
差分 + TreeMap
- 使用 TreeMap 存下出现的区间边界以及对应差分数组的值,即对于给定区间 [start, end],在 TreeMap 中放入 start,值为当前已有值(如果没有则为 0) + 1,在 TreeMap 中放入 end,值为当前已有值(如果没有则为 0) - 1
- 每次放入区间后,当前单个时刻重复日程的最大值即为 TreeMap 对应值的集合对应前缀和的最大值
代码:
public class MyCalendarThree {
// 存差分数组的有序集合
TreeMap<Integer, Integer> map;
public MyCalendarThree() {
map = new TreeMap<>();
}
public int book(int start, int end) {
// 放入区间边界
map.put(start, map.getOrDefault(start, 0) + 1);
map.put(end, map.getOrDefault(end, 0) - 1);
int max = 0;
int count = 0;
// 统计前缀和的最大值
for (int v : map.values()) {
count += v;
max = Math.max(max, count);
}
return max;
}
}