You are implementing a program to use as your calendar. We can add a new event if adding the event will not cause a triple booking.
A triple booking happens when three events have some non-empty intersection (i.e., some moment is common to all the three events.).
The event can be represented as a pair of integers start and end that represents a booking on the half-open interval [start, end), the range of real numbers x such that start <= x < end.
Implement the MyCalendarTwo class:
MyCalendarTwo() Initializes the calendar object.boolean book(int start, int end) Returns 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.Input
["MyCalendarTwo", "book", "book", "book", "book", "book", "book"]
[[], [10, 20], [50, 60], [10, 40], [5, 15], [5, 10], [25, 55]]
Output
[null, true, true, true, false, true, true]
class MyCalendarTwo:
def __init__(self):
self.tree = collections.defaultdict(int)
self.lazy = collections.defaultdict(int)
def query(self, start: int, end: int, l: int, r: int, idx: int) -> int:
if r < start or end < l: return 0
if start <= l and r <= end: return self.tree[idx]
m = (l + r) >> 1
l_m = self.query(start, end, l, m, (idx << 1) + 1)
r_m = self.query(start, end, m + 1, r, (idx << 1) + 2)
return max(l_m, r_m) + self.lazy[idx]
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:
m = (l + r) >> 1
self.update(start, end, l, m, (idx << 1) + 1)
self.update(start, end, m + 1, r, (idx << 1) + 2)
self.tree[idx] = self.lazy[idx] + max(self.tree[(idx << 1) + 1], self.tree[(idx << 1) + 2])
def book(self, start: int, end: int) -> bool:
if self.query(start, end - 1, 0, int(10 ** 9), 0) >= 2: return False
self.update(start, end - 1, 0, int(10 ** 9), 0)
return True
There are several squares being dropped onto the X-axis of a 2D plane.
You are given a 2D integer array positions where positions[i] = [lefti, sideLengthi] represents the ith square with a side length of sideLengthi that is dropped with its left edge aligned with X-coordinate lefti.
Each square is dropped one at a time from a height above any landed squares. It then falls downward (negative Y direction) until it either lands on the top side of another square or on the X-axis. A square brushing the left/right side of another square does not count as landing on it. Once it lands, it freezes in place and cannot be moved.
After each square is dropped, you must record the height of the current tallest stack of squares.
Return an integer array ans where ans[i] represents the height described above after dropping the ith square.
输入:positions = [[1,2],[2,3],[6,1]]
输出:[2,5,5]