729. My Calendar I

吸等 (celingKey 是有等於的

Though1

class MyCalendar {

    TreeMap<Integer, Integer> map;
    public MyCalendar() {
        map = new TreeMap<>();
    }
    
    public boolean book(int start, int end) {
        Integer later = map.ceilingKey(start);
        Integer ealier = map.floorKey(start);
        if (later != null && end > later) {
            return false;
        }
        if (ealier != null && map.get(ealier) > start) {
            return false;
        }
        map.put(start, end);
        return true;
    }
}

/**
T: O(nlogn)
S: O(n)

use start as key to compare in TreeMap!

4 cases:

     10       x    -> later = null, ealier = 10, get(ealier) > s
        s e

     10      x          -> later = null, , ealier = 10, get(ealier) > s
          s      e

     10      x       -> later = 10, e > later
  s      e  

       10      x
  s                   e    -> later = 10        , e > later    


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

ps: only start can be compare by key

5 10
case1 
  
  10       20
      
      
s      e  

       later == null
       so ealier is 10, so get(ealier) = 20 > s
  10       20
       s        e 

case2

    later = null
    so earlier is 10,   get(ealier) = 20 > s       
   10       20
       s e
 






 */

thought 2

only care when can put (simpler)

這題比較特別, treeMap 放的是 (start, end), key is start value

use lowerKey()

Though 3 - can used for Calender 2 (n^2)

use sweep line, but need to iterate map, so time complexity is worse

use floorKey(), ceilingKey()

sweep-line

also suit for 731, just change the max > ?

T: O(nlogn + n^2) = O(n^2), n times to call book()

S: O(n)

Last updated

Was this helpful?