295. Find Median from Data Stream
The median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value and the median is the mean of the two middle values.
- For example, for
arr = [2,3,4]
, the median is3
. - For example, for
arr = [2,3]
, the median is(2 + 3) / 2 = 2.5
.
Note: Two heap
Python's heapq is min heap. We negate values to get max heap.
The chosen policy here is to allow one more item to maxQ the lower
half queue when there are odd number of elements.
class MedianFinder:
def __init__(self):
self.maxQ = [] # smaller half
self.minQ = [] # larger half
def addNum(self, num: int) -> None:
heapq.heappush(self.maxQ, -num)
heapq.heappush(self.minQ, -heapq.heappop(self.maxQ))
if len(self.maxQ) < len(self.minQ):
heapq.heappush(self.maxQ, -heapq.heappop(self.minQ))
def findMedian(self) -> float:
if len(self.maxQ) > len(self.minQ):
return -self.maxQ[0]
return (float)(-self.maxQ[0] + self.minQ[0]) / 2
Comments
Post a Comment