forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
finding-mk-average.py
63 lines (55 loc) · 1.71 KB
/
finding-mk-average.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
# Time: ctor: O(1)
# add_element: O(logn)
# calc_mkaverage: O(1)
# Space: O(m)
import collections
from sortedcontainers import SortedList
class MKAverage(object):
def __init__(self, m, k):
"""
:type m: int
:type k: int
"""
self.__m = m
self.__k = k
self.__dq = collections.deque()
self.__sl = SortedList()
self.__total = self.__first_k = self.__last_k = 0
def addElement(self, num):
"""
:type num: int
:rtype: None
"""
if len(self.__dq) == self.__m:
self.__remove(self.__dq.popleft())
self.__dq.append(num)
self.__add(num)
def calculateMKAverage(self):
"""
:rtype: int
"""
if len(self.__sl) < self.__m:
return -1
return (self.__total-self.__first_k-self.__last_k)//(self.__m-2*self.__k)
def __add(self, num):
self.__total += num
idx = self.__sl.bisect_left(num)
if idx < self.__k:
self.__first_k += num
if len(self.__sl) >= self.__k:
self.__first_k -= self.__sl[self.__k-1]
if idx > len(self.__sl)-self.__k:
self.__last_k += num
if len(self.__sl) >= self.__k:
self.__last_k -= self.__sl[-self.__k]
self.__sl.add(num)
def __remove(self, num):
self.__total -= num
idx = self.__sl.index(num)
if idx < self.__k:
self.__first_k -= num
self.__first_k += self.__sl[self.__k]
elif idx > (len(self.__sl)-1)-self.__k:
self.__last_k -= num
self.__last_k += self.__sl[-1-self.__k]
self.__sl.remove(num)