|
| 1 | +# Find Median from Data Stream |
| 2 | +# https://leetcode.com/problems/find-median-from-data-stream/ |
| 3 | + |
| 4 | +class MedianFinder(object): |
| 5 | + |
| 6 | + def __init__(self): |
| 7 | + # holds all elements greater than median |
| 8 | + self.minHeap = [] |
| 9 | + # holds all elements smaller than median. |
| 10 | + self.maxHeap = [] |
| 11 | + """ |
| 12 | + initialize your data structure here. |
| 13 | + """ |
| 14 | + |
| 15 | + def addToMinHeap(self, num): |
| 16 | + # add number to min heap |
| 17 | + heapq.heappush(self.minHeap, num) |
| 18 | + # if length of heap is more then pop the element and add to max heap |
| 19 | + if (len(self.minHeap) > len(self.maxHeap)+1): |
| 20 | + element = heapq.heappop(self.minHeap) |
| 21 | + self.addToMaxHeap(element) |
| 22 | + |
| 23 | + def addToMaxHeap(self, num): |
| 24 | + # add number to max heap |
| 25 | + self.maxHeap.append(num) |
| 26 | + heapq._heapify_max(self.maxHeap) |
| 27 | + # if length of heap is more then pop the item and add to min Heap |
| 28 | + if (len(self.maxHeap) > len(self.minHeap)+1): |
| 29 | + element = self.maxHeap.pop(0) |
| 30 | + heapq._heapify_max(self.maxHeap) |
| 31 | + self.addToMinHeap(element) |
| 32 | + |
| 33 | + def addNum(self, num): |
| 34 | + # if both heaps are empty |
| 35 | + if ((not self.minHeap) and (not self.maxHeap)): |
| 36 | + self.addToMinHeap(num) |
| 37 | + return |
| 38 | + # if max heap is empty but min heap is not. |
| 39 | + if ((not self.maxHeap) and self.minHeap): |
| 40 | + # if top of min heap < num (because min heap needs to hold elements greater than median) |
| 41 | + if (self.minHeap[0] < num): |
| 42 | + # pop the top from min heap and add to max heap |
| 43 | + topMinElement = heapq.heappop(self.minHeap) |
| 44 | + self.addToMaxHeap(topMinElement) |
| 45 | + # add current element to min heap |
| 46 | + self.addToMinHeap(num) |
| 47 | + return |
| 48 | + # if both heaps have elements |
| 49 | + if (self.minHeap and self.maxHeap): |
| 50 | + # max heap contains elements from 0 to median |
| 51 | + if (num < self.maxHeap[0]): |
| 52 | + self.addToMaxHeap(num) |
| 53 | + else: |
| 54 | + self.addToMinHeap(num) |
| 55 | + """ |
| 56 | + :type num: int |
| 57 | + :rtype: None |
| 58 | + """ |
| 59 | + |
| 60 | + def findMedian(self): |
| 61 | + if (len(self.minHeap) == len(self.maxHeap)): |
| 62 | + return float(self.minHeap[0]+self.maxHeap[0])/float(2) |
| 63 | + if (len(self.minHeap) > len(self.maxHeap)): |
| 64 | + return self.minHeap[0] |
| 65 | + return self.maxHeap[0] |
| 66 | + """ |
| 67 | + :rtype: float |
| 68 | + """ |
| 69 | + |
| 70 | + |
| 71 | + |
| 72 | +# Your MedianFinder object will be instantiated and called as such: |
| 73 | +# obj = MedianFinder() |
| 74 | +# obj.addNum(num) |
| 75 | +# param_2 = obj.findMedian() |
0 commit comments