Monday, October 19, 2015

LeetCode [295] Find Median from Data Stream


295. Find Median from Data Stream
Hard

Median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle value.

For example,

[2,3,4], the median is 3

[2,3], the median is (2 + 3) / 2 = 2.5

Design a data structure that supports the following two operations:

  • void addNum(int num) - Add a integer number from the data stream to the data structure.
  • double findMedian() - Return the median of all elements so far.

 

Example:

addNum(1)
addNum(2)
findMedian() -> 1.5
addNum(3) 
findMedian() -> 2

 

Follow up:

  1. If all integer numbers from the stream are between 0 and 100, how would you optimize it?
  2. If 99% of all integer numbers from the stream are between 0 and 100, how would you optimize it?
 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
class MedianFinder {
    priority_queue<int> q1;
    priority_queue<int, vector<int>, greater<int>> q2;
public:

    // Adds a number into the data structure.
    void addNum(int num) {
        if(q1.size()>q2.size()){
            if(num>=q1.top()) q2.push(num);               
            else{
                q2.push(q1.top());
                q1.pop();
                q1.push(num);
            }
        }else{
            if(!q2.empty()&&num>=q2.top()){
                q1.push(q2.top());
                q2.pop();
                q2.push(num);
            }else q1.push(num);
        }
    }

    // Returns the median of current data stream
    double findMedian() {
        if(q1.size()>q2.size()){
            return q1.top();
        }else{
            return (q1.top()+q2.top())/2.0;
        }
    }
};

 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
class MedianFinder {
    PriorityQueue<Integer> pq1 = new PriorityQueue<>((a,b)-> b-a);
    PriorityQueue<Integer> pq2 = new PriorityQueue<Integer>();

    /** initialize your data structure here. */
    public MedianFinder() {
        
    }
    
    public void addNum(int num) {
        if(!pq2.isEmpty() && num>=pq2.peek()){
            pq2.add(num);
        }else{
            pq1.add(num);
        }

        if(pq1.size()-1>pq2.size()) pq2.add(pq1.poll());
        if(pq2.size()-1>pq1.size()) pq1.add(pq2.poll());
    }
    
    public double findMedian() {
        if(pq1.size()==pq2.size()){
            return (double)(pq1.peek()+pq2.peek())/2.0;
        }else if(pq1.size()>pq2.size()) return pq1.peek();
        else return pq2.peek();
    }
}

/**
 * Your MedianFinder object will be instantiated and called as such:
 * MedianFinder obj = new MedianFinder();
 * obj.addNum(num);
 * double param_2 = obj.findMedian();
 */

No comments:

Post a Comment