[LeetCode] 295. Find Median from Data Stream_hard tag: Heap Need to update the follow up question?

Median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle value.

For example,

[2,3,4], the median is 3

[2,3], the median is (2 + 3) / 2 = 2.5

Design a data structure that supports the following two operations:

  • void addNum(int num) - Add a integer number from the data stream to the data structure.
  • double findMedian() - Return the median of all elements so far.

 

Example:

addNum(1)
addNum(2)
findMedian() -> 1.5
addNum(3) 
findMedian() -> 2

 

Follow up:

  1. If all integer numbers from the stream are between 0 and 100, how would you optimize it?
  2. If 99% of all integer numbers from the stream are between 0 and 100, how would you optimize it?

这个题目思路就是用一个maxHeap, minHeap去维护目前看到的data stream.

1. add num, 用num 去跟median比较,如果<=median,放在maxHeap, else 放在minHeap

2. 再根据len(minHeap) 和len(maxHeap), 分别pop,push,保证len(maxHeap) == len(minHeap)  or += 1

3. Find median, if len(maxHeap) == len(minHeap), then (maxHeap[0] + minHeap[0])/2.0, else maxHeap[0]

 

Code

import heapq
class MedianFinder:

    def __init__(self):
        """
        initialize your data structure here.
        """
        self.maxHeap = []
        self.minHeap = []    

    def addNum(self, num):
        """
        :type num: int
        :rtype: None
        """
        median = self.findMedian()
        if median is None or num <= median:
            heapq.heappush(self.maxHeap, -num)
        else:
            heapq.heappush(self.minHeap, num)
        if len(self.maxHeap) > len(self.minHeap) + 1:
            heapq.heappush(self.minHeap, -heapq.heappop(self.maxHeap))
        elif len(self.maxHeap) < len(self.minHeap):
            heapq.heappush(self.maxHeap, -heapq.heappop(self.minHeap))
    
    def findMedian(self):
        """
        :rtype: float
        """        
        if len(self.maxHeap) == len(self.minHeap) and self.maxHeap:
            return (-self.maxHeap[0] + self.minHeap[0])/2.0
        elif len(self.maxHeap) > len(self.minHeap):
            return -self.maxHeap[0]

 

上一篇:D. Max Median(Codeforces Round #703 (Div. 2)题解)


下一篇:火币智能链开发之gasprice