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 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.

For example:

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

思路:这题正好在《剑指Offer》上见过,是用最大堆和最小堆来分别保存数据流的左半部分和右半部分,这样可以根据数据流长度的奇偶性来直接用最大堆最大值或者最大堆最大值和最小堆最小值的一半求得中位数。具体方法是,数据流中,奇数位数和偶数位数分别放入最小堆和最大堆,但是如何保证最大堆的最大值小于最小堆的最小值呢?只要当待加入最大堆的数大于最小堆的最小数,则把最大堆的最大数加入最小堆中,再把待加入数加入最大堆中。另一类反之,具体看代码:

class MedianFinder(object):
    import heapq
    def __init__(self):
        """
        initialize your data structure here.
        """
        self.heaps,self.heapb = [],[]
        self.cnt = 0

    def addNum(self, num):
        """
        :type num: int
        :rtype: void
        """
        if self.cnt%2 == 0:
            if self.heaps and self.heaps[0] < num:
                heapq.heappush(self.heapb,-heapq.heappop(self.heaps))
                heapq.heappush(self.heaps,num)
            else:
                heapq.heappush(self.heapb,-num)
        else:
            if self.heapb and -self.heapb[0] > num:
                heapq.heappush(self.heaps,-heapq.heappop(self.heapb))
                heapq.heappush(self.heapb,-num)
            else:
                heapq.heappush(self.heaps,num)
        self.cnt += 1    

    def findMedian(self):
        """
        :rtype: float
        """
        # print self.heapb,self.heaps
        if self.cnt:
            if self.cnt%2!=0:
                return -self.heapb[0]
            else:
                return (-self.heapb[0]+self.heaps[0])/2.0
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值