题目描述
如何得到一个数据流中的中位数?如果从数据流中读出奇数个数值,那么中位数就是所有数值排序之后位于中间的数值。如果从数据流中读出偶数个数值,那么中位数就是所有数值排序之后中间两个数的平均值。我们使用Insert()方法读取数据流,使用GetMedian()方法获取当前读取数据的中位数。
思路
方法一:牛客网不支持导包,所以编译出错……但是按照剑指offer上的思路来说,理应使用最大堆、最小堆的方法来做~
import heapq
class Solution:
def __init__(self):
self.big_nums = []
self.small_nums = []
self.cnt = 0
def Insert(self, num):
# write code here
self.cnt += 1
if self.cnt%2 == 0:
heapq.heappush(self.big_nums,num)
big = heapq.nlargest(1,self.big_nums)
heapq.heappush(self.small_nums,num)
else:
small = heapq.heappushpop(self.small_nums,num)
heapq.heappush(self.big_nums,small)
def GetMedian(self,n=None):
# write code here
if self.cnt%2 == 0:
big = heapq.nlargest(1,self.big_nums)
small = heapq.heappop(self.small_nums)
res = (big[0]+small)/2
else:
res = heapq.nlargest(1,self.big_nums)
return res
方法二:
# -*- coding:utf-8 -*-
class Solution:
def __init__(self):
self.nums = []
def Insert(self, num):
# write code here
self.nums.append(num)
def GetMedian(self,n=None):
# write code here
self.nums.sort()
if len(self.nums)%2 == 0:
res = (self.nums[len(self.nums)/2]+self.nums[len(self.nums)/2-1])/2.0
else:
res = self.nums[len(self.nums)//2]
return res