ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

数据流中的中位数

2022-05-20 01:34:22  阅读:179  来源: 互联网

标签:self 中位数 len num 数据流 findMedian class def


 /**

 * Problem Statement

 

Design a class to calculate the median of a number stream. The class should have the following two methods:

 

* insertNum(int num): stores the number in the class

* findMedian(): returns the median of all numbers inserted in the class

 

If the count of numbers inserted in the class is even, the median will be the average of the middle two numbers.

 

Example

 

1. insertNum(3)

2. insertNum(1)

3. findMedian() -> output: 2

4. insertNum(5)

5. findMedian() -> output: 3

6. insertNum(4)

7. findMedian() -> output: 3.5

 

 * 

 * 

* */

 

也是leetcode中的一道题《剑指 Offer 41. 数据流中的中位数

 

暴力解决

最先想到的暴力解法:

class MedianFinder(object):

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

    def addNum(self, num):
        """
        :type num: int
        :rtype: None
        """
        self.l.append(num)
        self.l.sort()

    def findMedian(self):
        """
        :rtype: float
        """
        length = len(self.l)

        if length%2 == 1:
            return self.l[length/2]
        else:
            return float((self.l[length/2] + self.l[length/2-1]))/2.0
 

说明:

对输入元素进行排序,然后取出,如果用冒泡的话是O(n2) 如果是快排O(NlogN)

可以解决:

可以解决,但是不是最优解

 

 

这道题最优解使用两个堆

新建两个堆(较大的数字放入小顶堆,较小顶数字放入大顶堆) 

然后循环下面步骤:

1、新元素给大数小顶堆后,小顶堆pop(大数堆中最小的数)的数给到小数堆 

2、新元素给小数大顶堆后,大顶堆pop(小数堆中最大的数)的数给到大数堆

这里画了一个示意图:

from heapq import *

class MedianFinder:
    def __init__(self):
        self.A = [] # 大数小顶堆,存放较大的一半
        self.B = [] # 小数大顶堆,存放较小的一半

    def addNum(self, num: int):
        if len(self.A) != len(self.B):
            heappush(self.B, -heappushpop(self.A, num))
        else:
            heappush(self.A, -heappushpop(self.B, -num))

    def findMedian(self):
        return self.A[0] if len(self.A) != len(self.B) else (self.A[0] - self.B[0]) / 2.0

这里需要注意,因为python只有小顶堆

因此当我们使用大顶堆的时候,只需要将数字 ✖️ -1 即可,例如之前 1 2 3,变换后 -3 -2 -1,pop的时候再  ✖️ -1 恢复即可

 

标签:self,中位数,len,num,数据流,findMedian,class,def
来源: https://www.cnblogs.com/by-dream/p/16289367.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有