forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmy-calendar-iii.py
66 lines (53 loc) · 1.74 KB
/
my-calendar-iii.py
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# Time: O(nlogn) ~ O(n^2)
# Space: O(n)
import bisect
class MyCalendarThree(object):
def __init__(self):
self.__books = [[-1, 0]]
self.__count = 0
def book(self, start, end):
"""
:type start: int
:type end: int
:rtype: int
"""
i = bisect.bisect_right(self.__books, [start, float("inf")])
if self.__books[i-1][0] == start:
i -= 1
else:
self.__books.insert(i, [start, self.__books[i-1][1]])
j = bisect.bisect_right(self.__books, [end, float("inf")])
if self.__books[j-1][0] == end:
j -= 1
else:
self.__books.insert(j, [end, self.__books[j-1][1]])
for k in xrange(i, j):
self.__books[k][1] += 1
self.__count = max(self.__count, self.__books[k][1])
return self.__count
# Time: O(n^2)
# Space: O(n)
class MyCalendarThree2(object):
def __init__(self):
self.__books = []
def book(self, start, end):
"""
:type start: int
:type end: int
:rtype: int
"""
i = bisect.bisect_left(self.__books, (start, 1))
if i < len(self.__books) and self.__books[i][0] == start:
self.__books[i] = (self.__books[i][0], self.__books[i][1]+1)
else:
self.__books.insert(i, (start, 1))
j = bisect.bisect_left(self.__books, (end, 1))
if j < len(self.__books) and self.__books[j][0] == end:
self.__books[j] = (self.__books[j][0], self.__books[j][1]-1)
else:
self.__books.insert(j, (end, -1))
result, cnt = 0, 0
for book in self.__books:
cnt += book[1]
result = max(result, cnt)
return result