LC729. My Calendar I

https://leetcode.com/problems...

Medium
Google, Uber, Amazon, Twitch
class MyCalendar {
    private List events;

    public MyCalendar() {
        events = new ArrayList<>();
        //题目有输入限制,0 <= start < end <= 10^9
        //可以增加左右边界,方便计算
        events.add(new int[]{-1, 0});
        events.add(new int[]{1000000001, 1000000001});
    }
    public boolean book(int start, int end) {
        // 使用二分法查找可以插入的位置
        int left = 0, right = events.size() - 1;
        while (left + 1 < right) {
            int mid = left + (right - left) / 2;
            int[] event = events.get(mid);
            if (start == event[0])  return false; // 如果start等于当前event的start,那么肯定有冲突,直接返回false
            if (start < event[0])   right = mid;  // 若start小于当前event的start,那么要往左边找
            else                    left = mid;   // 若start大于当前event的start,那么往右找
        }
        // 最终要安排插入的event就是坐落在left和right之间,看是否能插入
        if (start >= events.get(left)[1] && end <= events.get(right)[0]) {
            // 可以插入
            events.add(right, new int[]{start, end});
            return true;
        }
        // 不能插入
        return false;
    }
}

你可能感兴趣的:(算法javaleetcode)