Find Median from Data Stream
LeetCode 295 · ಕಠಿಣ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್ಥ್ರೂ
Two heaps: max-heap low half, min-heap high half.
ನಾನು Find Median from Data Stream (LeetCode 295) ಅನ್ನು ಹೀಗೆ ಪರಿಹರಿಸಿದೆ — Two Heaps ಪ್ಯಾಟರ್ನ್ನ ಒಂದು ಕಠಿಣ ಪ್ರಾಬ್ಲಮ್. ಕೆಳಗೆ: intuition, ಹಂತ ಹಂತದ approach, ನನ್ನ accepted Python ಕೋಡ್, animated test cases ಮತ್ತು line-by-line debugger.
ಕೆಳಗಿನ ವಿವರಣೆ ಇಂಗ್ಲಿಷ್ನಲ್ಲಿದೆ.
Intuition
Split the numbers into a lower half (max-heap) and an upper half (min-heap), keeping the halves balanced. The median is then at the top of one or both heaps.
Approach
- 1
addNum: push into the min-heap and move its smallest to the max-heap (heappushpop).
- 2
If the max-heap got bigger, move its largest back.
- 3
findMedian: odd count → min-heap top; even → average of both tops.
ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ
Two heapsPythonO(log n) per add
class MedianFinder:
#left side - max_heap
#right side - min_heap
#difference between right and left must be maximum 1
#first add on right and then add to left
def __init__(self):
self.max_heap = []
self.min_heap = []
def addNum(self, num: int) -> None:
heapq.heappush(self.max_heap,-heapq.heappushpop(self.min_heap,num))
if len(self.max_heap)>len(self.min_heap):
heapq.heappush(self.min_heap,-heapq.heappop(self.max_heap))
def findMedian(self) -> float:
return self.min_heap[0] if (len(self.max_heap)!=len(self.min_heap)) else (self.min_heap[0]+(-1)*self.max_heap[0])/2
# Your MedianFinder object will be instantiated and called as such:
# obj = MedianFinder()
# obj.addNum(num)
# param_2 = obj.findMedian()Find Median from Data Stream — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು
Find Median from Data Stream ಹಿಂದಿನ intuition ಏನು?
Split the numbers into a lower half (max-heap) and an upper half (min-heap), keeping the halves balanced. The median is then at the top of one or both heaps.
Find Median from Data Stream (LeetCode 295) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?
1. addNum: push into the min-heap and move its smallest to the max-heap (heappushpop). 2. If the max-heap got bigger, move its largest back. 3. findMedian: odd count → min-heap top; even → average of both tops.
Find Median from Data Stream ನ time ಮತ್ತು space complexity ಎಷ್ಟು?
Time: O(log n) add, O(1) median. Space: O(n). (Accepted approach: Two heaps.)
Find Median from Data Stream ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?
Python only has min-heaps — store negatives for the max-heap.