Skip to content

Commit 540a28d

Browse files
committed
2019-09-13
1 parent 8b82426 commit 540a28d

File tree

1 file changed

+22
-21
lines changed

1 file changed

+22
-21
lines changed

0295.数据流的中位数/0295-数据流的中位数.py

+22-21
Original file line numberDiff line numberDiff line change
@@ -1,41 +1,42 @@
11
from heapq import *
2+
# class Heaps(object):
3+
# def __init__(self):
4+
# self.min_heap = []
5+
# self.max_heap = []
6+
7+
# def __
28
class MedianFinder(object):
3-
# 维护两个堆,一个大顶堆,一个小顶堆,小顶堆里的数比大顶堆里的数都要大,
4-
# 如果有两个潜在的中位数(两个堆size相同),数据流的中位数就是两个堆顶之和除以2
5-
# 如果只有一个中位数,就看size更小的那个堆的堆顶
6-
# 如果新进来的数比小顶堆的数要小,就把它插入大顶堆
7-
# 如果新进来的数比小顶堆的数要大,就把它插入小顶堆
8-
# 调整两个堆,使得size 差最大为1
9+
910
def __init__(self):
1011
"""
1112
initialize your data structure here.
1213
"""
13-
self.max_h = list()
14-
self.min_h = list()
15-
heapify(self.max_h)
16-
heapify(self.min_h)
17-
14+
self.min_heap = []
15+
self.max_heap = []
16+
heapify(self.min_heap)
17+
heapify(self.max_heap)
1818

1919
def addNum(self, num):
2020
"""
2121
:type num: int
2222
:rtype: None
2323
"""
24-
heappush(self.min_h, num)
25-
heappush(self.max_h, -heappop(self.min_h))
26-
if len(self.max_h) > len(self.min_h):
27-
heappush(self.min_h, -heappop(self.max_h))
24+
heappush(self.min_heap, num)
25+
heappush(self.max_heap, -heappop(self.min_heap))
26+
if len(self.max_heap) > len(self.min_heap):
27+
heappush(self.min_heap, -heappop(self.max_heap))
28+
2829

2930
def findMedian(self):
3031
"""
3132
:rtype: float
3233
"""
33-
max_len = len(self.max_h)
34-
min_len = len(self.min_h)
35-
if max_len == min_len: #有两个候选中位数
36-
return (self.min_h[0] + -self.max_h[0]) / 2.
37-
else:#小顶堆的size 一定 >= 大顶堆的size,所以答案就是小顶堆的堆顶
38-
return self.min_h[0] / 1.
34+
l_min_heap = len(self.min_heap)
35+
l_max_heap = len(self.max_heap)
36+
if l_min_heap == l_max_heap:
37+
return (self.min_heap[0] - self.max_heap[0]) /2.
38+
else:
39+
return self.min_heap[0]/1.
3940

4041

4142

0 commit comments

Comments
 (0)