295 Find Median from Data Stream

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.

Examples:

[2,3,4], the median is3

[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.
import heapq

class MedianFinder(object):
    def __init__(self):
        """
        initialize your data structure here.
        """
        self.left = []
        self.right = []


    def addNum(self, num):
        """
        :type num: int
        :rtype: void
        """
        if len(self.left) == len(self.right):
            heapq.heappush(self.left, -num)
            leftMax = -heapq.heappop(self.left)
            heapq.heappush(self.right, leftMax)
        else:
            heapq.heappush(self.right, num)
            rightMin = -heapq.heappop(self.right)
            heapq.heappush(self.left, rightMin)

    def findMedian(self):
        """
        :rtype: float
        """
        if not self.left and not self.right:
            return None

        if len(self.left) == len(self.right):
            return (-self.left[0]+self.right[0])/2.0
        else:
            return self.right[0]

s = MedianFinder()
for num in [-2, -3]:
    s.addNum(num)
print s.findMedian()

results matching ""

    No results matching ""