Skip to content

Commit cf9327f

Browse files
committed
Week 13
1 parent 1f5171d commit cf9327f

1 file changed

Lines changed: 26 additions & 0 deletions

File tree

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import heapq
2+
3+
class MedianFinder:
4+
5+
def __init__(self):
6+
self.max_heap = []
7+
self.min_heap = []
8+
9+
def addNum(self, num: int) -> None:
10+
if not self.min_heap or self.min_heap[0] <= num:
11+
heapq.heappush(self.min_heap, num)
12+
else:
13+
heapq.heappush(self.max_heap, -num)
14+
15+
if len(self.min_heap) < len(self.max_heap):
16+
heapq.heappush(self.min_heap, -heapq.heappop(self.max_heap))
17+
elif len(self.min_heap) > len(self.max_heap) + 1:
18+
heapq.heappush(self.max_heap, -heapq.heappop(self.min_heap))
19+
20+
def findMedian(self) -> float:
21+
if len(self.min_heap) == len(self.max_heap):
22+
return (self.min_heap[0]-self.max_heap[0])/2
23+
else:
24+
return self.min_heap[0]
25+
26+

0 commit comments

Comments
 (0)