1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| class MyCalendarTwo:
def __init__(self): self.tree = defaultdict(int) self.lazy = defaultdict(int)
def update(self, start: int, end: int, l: int, r: int, idx: int): if r < start or end < l: return if start <= l and r <= end: self.tree[idx] += 1 self.lazy[idx] += 1 else: mid = (l + r) // 2 self.update(start, end, l, mid, idx * 2) self.update(start, end, mid + 1, r, idx * 2 + 1) self.tree[idx] = self.lazy[idx] + max(self.tree[idx * 2], self.tree[idx * 2 + 1]) def check(self, start: int, end: int, l: int, r: int, idx: int): if r < start or end < l: return 0 if start <= l and r <= end: return self.tree[idx] else: mid = (l+r) //2 return self.lazy[idx] + max(self.check(start, end, l, mid, idx*2), self.check(start, end, mid + 1, r, idx*2+1))
def book(self, startTime: int, endTime: int) -> bool: ret = self.check(startTime, endTime - 1, 0, 10 ** 9, 1) if ret >= 2: return False else: self.update(startTime, endTime - 1, 0, 10 ** 9, 1) return True
|