[leetcode]731. My Calendar II

[leetcode]731. My Calendar II


Analysis

出太阳啦~—— [每天刷题并不难0.0]

Implement a MyCalendarTwo class to store your events. A new event can be added if adding the event will not cause a triple booking.
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 triple booking happens when three events have some non-empty intersection (ie., there is some time that is common to all 3 events.)
For each call to the method MyCalendar.book, return true if the event can be added to the calendar successfully without causing a triple booking. Otherwise, return false and do not add the event to the calendar.
Your class will be called like this: MyCalendar cal = new MyCalendar(); MyCalendar.book(start, end)
在这里插入图片描述

Explanation:

跟My Calendar I的区别就是这里允许区间有一次重叠,但是不允许两次重叠。My Calendar I指路: https://blog.csdn.net/weixin_32135877/article/details/84748187

Implement

class MyCalendarTwo {
public:
    MyCalendarTwo() {
        
    }
    
    bool book(int start, int end) {
        auto it = overlap1.lower_bound(start+1);
        if(it!=overlap1.end() && it->second<end)
            return false;
        it = overlap0.lower_bound(start+1);
        while(it != overlap0.end()){
            int s = it->second;
            int e = it->first;
            if(s > end)
                break;
            if(max(start, s) < min(end, e))
                overlap1[min(end,e)] = max(start,s);
            start = min(start, s);
            end = max(end, e);
            it = overlap0.erase(it);
        }
        overlap0[end] = start;
        return true;
    }
private:
    map<int, int> overlap0;
    map<int, int> overlap1;
};

/**
 * Your MyCalendarTwo object will be instantiated and called as such:
 * MyCalendarTwo obj = new MyCalendarTwo();
 * bool param_1 = obj.book(start,end);
 */

猜你喜欢

转载自blog.csdn.net/weixin_32135877/article/details/86503641