|
1 | 1 | from heapq import *
|
| 2 | +# class Heaps(object): |
| 3 | +# def __init__(self): |
| 4 | +# self.min_heap = [] |
| 5 | +# self.max_heap = [] |
| 6 | + |
| 7 | +# def __ |
2 | 8 | class MedianFinder(object):
|
3 |
| -# 维护两个堆,一个大顶堆,一个小顶堆,小顶堆里的数比大顶堆里的数都要大, |
4 |
| -# 如果有两个潜在的中位数(两个堆size相同),数据流的中位数就是两个堆顶之和除以2 |
5 |
| -# 如果只有一个中位数,就看size更小的那个堆的堆顶 |
6 |
| -# 如果新进来的数比小顶堆的数要小,就把它插入大顶堆 |
7 |
| -# 如果新进来的数比小顶堆的数要大,就把它插入小顶堆 |
8 |
| -# 调整两个堆,使得size 差最大为1 |
| 9 | + |
9 | 10 | def __init__(self):
|
10 | 11 | """
|
11 | 12 | initialize your data structure here.
|
12 | 13 | """
|
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) |
18 | 18 |
|
19 | 19 | def addNum(self, num):
|
20 | 20 | """
|
21 | 21 | :type num: int
|
22 | 22 | :rtype: None
|
23 | 23 | """
|
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 | + |
28 | 29 |
|
29 | 30 | def findMedian(self):
|
30 | 31 | """
|
31 | 32 | :rtype: float
|
32 | 33 | """
|
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. |
39 | 40 |
|
40 | 41 |
|
41 | 42 |
|
|
0 commit comments