Header Ad

Leetcode Find Median from Data Stream problem solution

In this Leetcode Find Median from Data Stream problem solution, The median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value and the median is the mean of the two middle values.

For example, for arr = [2,3,4], the median is 3.

For example, for arr = [2,3], the median is (2 + 3) / 2 = 2.5.

Implement the MedianFinder class:

  1. MedianFinder() initializes the MedianFinder object.
  2. void addNum(int num) adds the integer num from the data stream to the data structure.

double findMedian() returns the median of all elements so far. Answers within 10-5 of the actual answer will be accepted.

Leetcode Find Median from Data Stream problem solution


Problem solution in Python.

class MedianFinder:

    def __init__(self):
        """
        initialize your data structure here.
        """
        self.maxHeap = []
        self.minHeap = []
        self.median = 0.0
    
    def addNum(self, num: int) -> None:
        if num >= self.median:
            heapq.heappush(self.minHeap, num)
        else:
            heapq.heappush(self.maxHeap,( -1 * num))
        if abs(len(self.maxHeap) - len(self.minHeap)) > 1:
            if len(self.maxHeap) > len(self.minHeap):
                n = heapq.heappop(self.maxHeap)
                n = -1 * n
                heapq.heappush(self.minHeap, n)
            else:
                n = heapq.heappop(self.minHeap)
                heapq.heappush(self.maxHeap, (-1 * n))
        if len(self.maxHeap) > len(self.minHeap):
            self.median = -1 * self.maxHeap[0]
        elif len(self.maxHeap) < len(self.minHeap):
            self.median = self.minHeap[0]
        else:
            self.median = (self.minHeap[0] + (-1 * self.maxHeap[0])) / 2
    
    def findMedian(self) -> float:
        return self.median



Problem solution in Java.

class MedianFinder {
    Queue<Integer> upHeap;
    Queue<Integer> downHeap;
    public MedianFinder() {
        upHeap = new PriorityQueue<>((a, b) -> b-a);
        downHeap = new PriorityQueue<>();
    }

    public void addNum(int num) {
        if(upHeap.size() == 0){
            upHeap.offer(num);
            return;
        }
        if(upHeap.size() > downHeap.size()){
            if(num <= upHeap.peek()){
                upHeap.offer(num);
                downHeap.offer(upHeap.poll());
            }
            else{
                downHeap.offer(num);
            }
        }
        else{
            if(num <= upHeap.peek()){
                upHeap.offer(num);
            }
            else{
                downHeap.offer(num);
                upHeap.offer(downHeap.poll());
            }
        }
    }
    
    public double findMedian() {
        if(upHeap.size() > downHeap.size()){
            return upHeap.peek();
        }
        else{
            return (upHeap.peek() + downHeap.peek()) / 2.0;
        }
    }
}


Problem solution in C++.

class MedianFinder {
public:
    /** initialize your data structure here. */
    //create 1 Max Heap and 1 Min Heap
    priority_queue<int> maxHeap;
    priority_queue<int, vector<int>,greater<int> > minHeap;
    int s1 , s2;
    MedianFinder() {
    }
    
    void addNum(int num) {
        if(maxHeap.empty()) {
            maxHeap.push(num);
        } else if(num > maxHeap.top()) {
            minHeap.push(num);
        } else {
            maxHeap.push(num);
        }
        if(abs((int)maxHeap.size() - (int)minHeap.size()) > 1 ) {
            int ele;
            if(maxHeap.size() > minHeap.size()) {
                ele = maxHeap.top();
                maxHeap.pop();
                minHeap.push(ele);
            } else {
                ele = minHeap.top();
                minHeap.pop();
                maxHeap.push(ele);
            }

        }
    }
    
    double findMedian() {
        s1 = maxHeap.size(),
        s2 = minHeap.size();
        if((s1 + s2) % 2 == 0) {
            double ans = ((double)maxHeap.top() + (double)minHeap.top() ) / (double)2;
            return ans;
        } else {
            if(s1 > s2)
                return maxHeap.top();
            else 
                return minHeap.top();
        }
    }
};


Post a Comment

0 Comments