-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
count-integers-in-intervals.py
42 lines (36 loc) · 1.03 KB
/
count-integers-in-intervals.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
# Time: ctor: O(1)
# add: O(logn), amortized
# count: O(1)
# Space: O(n)
from sortedcontainers import SortedList
# design, sortedlist
class CountIntervals(object):
def __init__(self):
self.__sl = SortedList()
self.__cnt = 0
def add(self, left, right):
"""
:type left: int
:type right: int
:rtype: None
"""
i = self.__sl.bisect_right((left,))
if i-1 >= 0 and self.__sl[i-1][1]+1 >= left:
i -= 1
left = self.__sl[i][0]
to_remove = []
for i in xrange(i, len(self.__sl)):
if not (right+1 >= self.__sl[i][0]):
break
right = max(right, self.__sl[i][1])
self.__cnt -= self.__sl[i][1]-self.__sl[i][0]+1
to_remove.append(i)
while to_remove:
del self.__sl[to_remove.pop()]
self.__sl.add((left, right))
self.__cnt += right-left+1
def count(self):
"""
:rtype: int
"""
return self.__cnt