forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 1
/
find-median-from-data-stream.py
64 lines (58 loc) · 1.89 KB
/
find-median-from-data-stream.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# Time: O(nlogn) for total n addNums, O(logn) per addNum, O(1) per findMedian.
# Space: O(n), total space
# Median is the middle value in an ordered integer list.
# If the size of the list is even, there is no middle value.
# So the median is the mean of the two middle value.
#
# Examples:
# [2,3,4] , the median is 3
#
# [2,3], the median is (2 + 3) / 2 = 2.5
#
# Design a data structure that supports the following two operations:
#
# void addNum(int num) - Add a integer number from the data stream to the data structure.
# double findMedian() - Return the median of all elements so far.
# For example:
#
# add(1)
# add(2)
# findMedian() -> 1.5
# add(3)
# findMedian() -> 2
# Heap solution.
from heapq import heappush, heappop
class MedianFinder:
def __init__(self):
"""
Initialize your data structure here.
"""
self.__max_heap = []
self.__min_heap = []
def addNum(self, num):
"""
Adds a num into the data structure.
:type num: int
:rtype: void
"""
# Balance smaller half and larger half.
if not self.__max_heap or num > -self.__max_heap[0]:
heappush(self.__min_heap, num)
if len(self.__min_heap) > len(self.__max_heap) + 1:
heappush(self.__max_heap, -heappop(self.__min_heap))
else:
heappush(self.__max_heap, -num)
if len(self.__max_heap) > len(self.__min_heap):
heappush(self.__min_heap, -heappop(self.__max_heap))
def findMedian(self):
"""
Returns the median of current data stream
:rtype: float
"""
return (-self.__max_heap[0] + self.__min_heap[0]) / 2.0 \
if len(self.__min_heap) == len(self.__max_heap) \
else self.__min_heap[0]
# Your MedianFinder object will be instantiated and called as such:
# mf = MedianFinder()
# mf.addNum(1)
# mf.findMedian()