-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathFind-Median-From-Data-Stream.py
99 lines (80 loc) · 2.56 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
###python Solution 1:
class MedianFinder:
def __init__(self):
"""
initialize your data structure here.
"""
self.store=[]
def addNum(self, num: int) -> None:
self.store.append(num)
def findMedian(self) -> float:
store=sorted(self.store)
n = len(self.store)
if n%2==0:
return (self.store[n//2]+self.store[n//2-1])/2.0
else:
return self.store[n//2]
# Your MedianFinder object will be instantiated and called as such:
# obj = MedianFinder()
# obj.addNum(num)
# param_2 = obj.findMedian()
### Python Solution 2:
class MedianFinder:
def __init__(self):
"""
initialize your data structure here.
"""
self.store=[]
def insertSort(self,arr):
for i in range(1,len(arr)):
j = i-1
key = arr[i]
while j >= 0:
if arr[j] > key:
arr[j+1] = arr[j]
arr[j] = key
j -= 1
return arr
def addNum(self, num: int) -> None:
self.store.append(num)
self.store = self.insertSort(self.store)
def findMedian(self) -> float:
n = len(self.store)
if n%2==0:
return (self.store[n//2]+self.store[n//2-1])/2.0
else:
return self.store[n//2]
# Your MedianFinder object will be instantiated and called as such:
# obj = MedianFinder()
# obj.addNum(num)
# param_2 = obj.findMedian()
### Python Solution 3:
class MedianFinder:
def __init__(self):
"""
initialize your data structure here.
"""
self.count = 0
self.max_heap = []
self.min_heap = []
def addNum(self, num: int) -> None:
# 因为 Python 中的堆默认是小顶堆,所以要传入一个相反数,
# 才能模拟出大顶堆的效果
if self.count % 2 == 0:
heapq.heappush(self.max_heap, -num)
max_heap_top = heapq.heappop(self.max_heap)
heapq.heappush(self.min_heap,-max_heap_top)
else:
heapq.heappush(self.min_heap, num)
min_heap_top = heapq.heappop(self.min_heap)
heapq.heappush(self.max_heap,-min_heap_top)
self.count+=1
def findMedian(self) -> float:
if self.count % 2 == 0:
return (self.min_heap[0] - self.max_heap[0])/2.0
else:
return self.min_heap[0]
# Your MedianFinder object will be instantiated and called as such:
# obj = MedianFinder()
# obj.addNum(num)
# param_2 = obj.findMedian()