LeetCode 729/731. My Calendar I + II

My Calendar I

hash table + binary search,注意边界情况即可。

class MyCalendar {
private:
    map<int,int> m; // map[start] -> end
    
public:
    MyCalendar() {}
    
    bool book(int start, int end) {
        auto it=m.lower_bound(start);
        if (it!=m.end() && end>it->first) return false;
        if (it!=m.begin() && (--it)->second>start) return false;
        m[start] = end;
        return true;
    }
};

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

 

My Calendar II

方法一:沿用 My Calendar I 的思路,给overlap的时间段再建一个hashtable,判断overlap的时间有没有overlap。

https://leetcode.com/problems/my-calendar-ii/discuss/109519/JavaC++-Clean-Code-with-Explanation

 

方法二:Boundary Count

思路与 Number of Meeting Rooms at a Given Time 一致,只不过每次book都要计算一遍所有时刻有没有符合要求。

class MyCalendarTwo {
private:
    map<int,int> m; // time->num
public:
    MyCalendarTwo() {}
    
    bool book(int start, int end) {
        ++m[start]; --m[end];
        int sum=0;
        for (auto it=m.begin();it!=m.end();++it){
            if (it->second+sum >= 3){
                if (--m[start]==0) m.erase(start); 
                ++m[end];
                return false;
            }
            sum += it->second;
        }
        return true;
    }
};

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

时间复杂度 O(n^2)

 

转载于:https://www.cnblogs.com/hankunyan/p/11075135.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值