forked from lupamo3-zz/coding-interview-gym
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Continuous_Median.py
98 lines (80 loc) · 3.09 KB
/
Continuous_Median.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
class ContinuousMedianHandler:
def __init__(self):
self.lowers = Heap(MAX_HEAP_FUNC, [])
self.greaters = Heap(MIN_HEAP_FUNC, [])
self.median = None
def insert(self, number):
if not self.lowers.length or number < self.lowers.peek():
self.lowers.insert(number)
else:
self.greaters.insert(number)
self.rebalannceHeap()
self.updateMedian()
def rebalannceHeap(self):
if self.lowers.length - self.greaters.length == 2:
self.greaters.insert(self.lowers.remove())
elif self.greaters.length - self.lowers.length == 2:
self.lowers.insert(self.greaters.remove())
def updateMedian(self):
if self.lowers.length == self.greaters.length:
self.median = (self.lowers.peek() + self.greaters.peek()) / 2
elif self.lowers.length > self.greaters.length:
self.median = self.lowers.peek()
else:
self.median = self.greaters.peek()
def getMedian(self):
return self.median
class Heap:
def __init__(self, comparisonFunc, array):
self.heap = self.buildHeap(array)
self.comparisonFunc = comparisonFunc
self.length = len(self.heap)
def buildHeap(self, array):
firstParentIdx = (len(array) - 2) // 2
for currentIdx in reversed(range(firstParentIdx + 1)):
self.shiftDown(currentIdx, len(array) - 1, array)
return array
def shiftDown(self, currentIdx, endIdx, heap):
childOneIdx = currentIdx * 2 + 1
while childOneIdx <= endIdx:
childTwoIdx = currentIdx * 2 + 2 if currentIdx * 2 + 2 <= endIdx else -1
if childTwoIdx != -1:
if self.comparisonFunc(heap[childTwoIdx], heap[childOneIdx]):
idxToSwap = childTwoIdx
else:
idxToSwap = childOneIdx
else:
idxToSwap = childOneIdx
if self.comparisonFunc(heap[idxToSwap], heap[currentIdx]):
self.swap(currentIdx, idxToSwap, heap)
currentIdx = idxToSwap
childOneIdx = currentIdx * 2 + 1
else:
return
def shiftUp(self, currentIdx, heap):
parentIdx = (currentIdx - 1) // 2
while currentIdx > 0:
if self.comparisonFunc(heap[currentIdx], heap[parentIdx]):
self.swap(currentIdx, parentIdx, heap)
currentIdx = parentIdx
parentIdx = (currentIdx - 1) // 2
else:
return
def peek(self):
return self.heap[0]
def remove(self):
self.swap(0, self.length - 1, self.heap)
valueToRemove = self.heap.pop()
self.length -= 1
self.shiftDown(0, self.length - 1, self.heap)
return valueToRemove
def insert(self, value):
self.heap.append(value)
self.length += 1
self.shiftUp(self.length - 1, self.heap)
def swap(self, i, j, array):
array[i], array[j] = array[j], array[i]
def MAX_HEAP_FUNC(a, b):
return a > b
def MIN_HEAP_FUNC(a, b):
return a < b