剑指offer 数据流中的中位数

数据流中的中位数

题目

类似于 Leetcode 295.数据流的中位数
如何得到一个数据流中的中位数?如果从数据流中读出奇数个数值,那么中位数就是所有数值排序之后位于中间的数值。如果从数据流中读出偶数个数值,那么中位数就是所有数值排序之后中间两个数的平均值。我们使用Insert()方法读取数据流,使用GetMedian()方法获取当前读取数据的中位数。

方法

方法1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# -*- coding:utf-8 -*-
import bisect
class Solution:
def __init__(self):
self.l=[]
def Insert(self, num):
# write code here
bisect.insort(self.l,num)

def GetMedian(self,n=None):
# write code here
b=(len(self.l)-1)/2
e=len(self.l)/2
return (self.l[b]+self.l[e])*1.0/2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# -*- 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()
n=len(self.nums)
if n &1==0:
return (self.nums[n//2-1]+self.nums[n//2])/2.0
else:
return self.nums[n//2]

方法2:采用两个堆

插入数据需要时间$O(n\lgn)$,获取中位数需要时间$O(1)$

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# -*- coding:utf-8 -*-
from heapq import *
class Solution:
def __init__(self):
self.small=[]
self.large=[]
def Insert(self, num):
# write code here
if len(self.small)==len(self.large):
heappush(self.large, -heappushpop(self.small,-num))
else:
heappush(self.small, -heappushpop(self.large,num))

def GetMedian(self,n=None):
# write code here
if len(self.small)==len(self.large):
return float(self.large[0]-self.small[0])/2.0
else:
return float(self.large[0])