729. My Calendar I (Solution 1)
package LeetCode_729 /** * 729. My Calendar I * https://leetcode.com/problems/my-calendar-i/description/ * https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-729-my-calendar-i/ * * Implement a MyCalendar class to store your events. * A new event can be added if adding the event will not cause a double booking. Your class will have the 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 double booking happens when two events have some non-empty intersection (ie., there is some time that is common to both events.) For each call to the method MyCalendar.book, return true if the event can be added to the calendar successfully without causing a double 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) * */ class MyCalendar() { /* * solution 1: brute force, Time complexity:O(n^2), Space complexity:O(n); * * solution 2: binary search(TreeMap), Time complexity:O(nlogn), Space complexity:O(n); * 1. key = start; * 2. floor: largest entry whose key <= query key; * 3. ceiling: smallest entry whose key > query key; * 4. check floor and ceiling each time; * overlapping situation: * floor.end > query.start OR ceiling.start < query.end * */ val booked = ArrayList<Pair<Int, Int>>() fun book(start: Int, end: Int): Boolean { for (book in booked) { val s = book.first val e = book.second //draw interval to understand!! if (Math.max(start, s) < Math.min(end, e)) { return false } } booked.add(Pair(start, end)) return true } } /** * Your MyCalendar object will be instantiated and called as such: * var obj = MyCalendar() * var param_1 = obj.book(start,end) */
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)