算法分析课每周练习 Find Median from Data Stream

来源:互联网 发布:java异步http请求post 编辑:程序博客网 时间:2024/06/14 03:06

题目

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 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.
from heapq import *class MedianFinder:    def __init__(self):        self.small = []  # the smaller half of the list, max heap (invert min-heap)        self.large = []  # the larger half of the list, min heap    def addNum(self, num):        if len(self.small) == len(self.large):            heappush(self.large, -heappushpop(self.small, -num))        else:            heappush(self.small, -heappushpop(self.large, num))    def findMedian(self):        if len(self.small) == len(self.large):            return float(self.large[0] - self.small[0]) / 2.0        else:            return float(self.large[0])

本来以为是用平衡搜索树做的,看了答案原来是维持两个堆,实现起来确实简单多了