-
Notifications
You must be signed in to change notification settings - Fork 2
/
main2.py
41 lines (34 loc) · 1.26 KB
/
main2.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
from heapq import heappush, heappop
class Solution:
def __init__(self):
self.maxHeap = []
self.minHeap = []
def medianSlidingWindow(self, nums, k):
result = []
for i in range(len(nums)):
self.rebalance(nums, i)
if i >= k - 1:
if k % 2 == 0:
result.append(self.minHeap[0] / 2 - self.maxHeap[0] / 2)
else:
result.append(-self.maxHeap[0])
toRemove = nums[i - k + 1]
if toRemove <= - self.maxHeap[0]:
self.remove(self.maxHeap, -toRemove)
else:
self.remove(self.minHeap, toRemove)
self.rebalance(nums, i)
return result
def remove(self, heap, ele):
idn = heap.index(ele)
heap[idn] = heap[-1]
del heap[-1]
if idn < len(heap):
heap._siftup(heap, idn)
heap._siftdown(heap, 0, idn)
def rebalance(self, nums, i):
heappush(self.maxHeap, -nums[i])
heappush(self.minHeap, -heappop(self.maxHeap))
if len(self.minHeap) > len(self.maxHeap):
heappush(self.maxHeap, -heappop(self.minHeap))
print(Solution.medianSlidingWindow([1, 3, -1, -3, 5, 3, 6, 7], 3))