295. Find Median from Data Stream

来源:互联网 发布:淘宝怎样买枪 编辑:程序博客网 时间:2024/04/30 15:37

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.
解题思路:我开始考虑使用插入排序来做,这样达到的时间复杂度为O(n),后面发现判题盘不过,估计题目要求的时间复杂度为O(logN),后面考虑用大根堆,小根堆来做。
class MedianFinder:    def __init__(self):        """        Initialize your data structure here.        """        self.data=[]    def addNum(self, num):        """        Adds a num into the data structure.        :type num: int        :rtype: void        """        self.data.append(num)        length=len(self.data)                if length>1:            j=length-2            while j>=0 and num < self.data[j]:                self.data[j+1]=self.data[j]                j-=1            self.data[j+1]=num    def findMedian(self):        """        Returns the median of current data stream        :rtype: float        """        length=len(self.data)        if length%2!=0:            return self.data[length/2]        else:            return (self.data[length/2-1]+self.data[length/2])/2

大根堆小根堆:
import heapqclass MedianFinder:    def __init__(self):        """        Initialize your data structure here.        """        self.minHeap=[]        self.maxHeap=[]    def addNum(self, num):        """        Adds a num into the data structure.        :type num: int        :rtype: void        """        if len(self.maxHeap)==len(self.minHeap):            heapq.heappush(self.maxHeap,-heapq.heappushpop(self.minHeap,num))        else:            heapq.heappush(self.minHeap,-heapq.heappushpop(self.maxHeap,-num))    def findMedian(self):        """        Returns the median of current data stream        :rtype: float        """        if len(self.maxHeap)==len(self.minHeap):            return (-self.maxHeap[0]+self.minHeap[0])/2.0        else:            return -self.maxHeap[0]# Your MedianFinder object will be instantiated and called as such:mf = MedianFinder()mf.addNum(1)mf.addNum(3)mf.addNum(2)print mf.findMedian()

参考博客:http://bookshadow.com/weblog/2015/10/19/leetcode-find-median-data-stream/


0 0
原创粉丝点击