Skip to content

Latest commit

 

History

History
executable file
·
187 lines (163 loc) · 4.89 KB

295.Find Median from Data Stream.md

File metadata and controls

executable file
·
187 lines (163 loc) · 4.89 KB

295.Find Median from Data Stream

Question

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: * If all integer numbers from the stream are between 0 and 100, how would you optimize it? * If 99% of all integer numbers from the stream are between 0 and 100, how would you optimize it?

Thinking:

  • Method 1:
    • 通过堆结构来实现,堆结构是通过优先级队列实现的。
    • 维护一个递增堆和一个递减堆。
    • 通过判断两个堆的size判断总数是奇数还是偶数。
class MedianFinder {
    private List<Integer> list;
    /** initialize your data structure here. */
    public MedianFinder() {
        this.list = new ArrayList<>();
    }

    public void addNum(int num) {
        list.add(num);
    }

    public double findMedian() {
        int size = list.size();
        if(size % 2 != 0)
            return (double)list.get(size / 2);
        else{
            return (double)(list.get(size / 2) + list.get(size / 2 - 1)) / 2;
        }
    }
}

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

Second time

  1. Use two priority queue to solve this quesiton.
  2. Imgur
class MedianFinder {
    /** initialize your data structure here. */
    PriorityQueue<Integer> min;
    PriorityQueue<Integer> max;
    public MedianFinder() {
        min = new PriorityQueue<>();
        max = new PriorityQueue<>(new Comparator<Integer>(){
            @Override
            public int compare(Integer n1, Integer n2){
                return n2 - n1;
            }
        });
    }
    public void addNum(int num) {
        max.offer(num);
        min.offer(max.poll());
        if(max.size() < min.size()) max.offer(min.poll());
    }
    public double findMedian() {
        if(max.size() > min.size()) return (double)max.peek();
        else return (double)(max.peek() + min.peek()) / 2;
    }
}
/**
 * Your MedianFinder object will be instantiated and called as such:
 * MedianFinder obj = new MedianFinder();
 * obj.addNum(num);
 * double param_2 = obj.findMedian();
 */

Third Time

  • Method 1: PriorityQueue
     class MedianFinder {
     	PriorityQueue<Integer> pq1;
     	PriorityQueue<Integer> pq2;
     	/** initialize your data structure here. */
     	public MedianFinder() {
     		pq2 = new PriorityQueue<>();
     		pq1 = new PriorityQueue<>(new Comparator<Integer>(){
     			@Override
     			public int compare(Integer a, Integer b){
     				return b - a;
     			}
     		});
     	}
     	
     	public void addNum(int num) {
     		pq1.offer(num);
     		pq2.offer(pq1.poll());
     		if(pq1.size() < pq2.size())
     			pq1.offer(pq2.poll());
     	}
     	
     	public double findMedian() {
     		if(pq1.size() == pq2.size()){
     			return (double)(pq1.peek() + pq2.peek()) / 2;
     		}else{
     			return (double) pq1.peek();
     		}
     	}
     }
    
     /**
      * Your MedianFinder object will be instantiated and called as such:
      * MedianFinder obj = new MedianFinder();
      * obj.addNum(num);
      * double param_2 = obj.findMedian();
      */

Amazon session

* Method 1: PriorityQueue
* Follow up:
	1. Count sort, record the appearance frequency of each number. Find the medium of according to the total numbers. O(100) = O(1)
	2. In this case, we need an integer array of length 100 and a hashmap for these numbers that are not in [0,100].
```Java
class MedianFinder {
	private PriorityQueue<Integer> minQ;    
	private PriorityQueue<Integer> maxQ;    
	/** initialize your data structure here. */
	public MedianFinder() {
		this.minQ = new PriorityQueue<>((a, b)->{
		   return a - b; 
		});
		this.maxQ = new PriorityQueue<>((a, b)->{
			return b - a;
		});
	}
	
	public void addNum(int num) {
		if(minQ.isEmpty() || num <= minQ.peek()){
			maxQ.offer(num);
			if(maxQ.size() > minQ.size()) minQ.offer(maxQ.poll());
		}else{
			minQ.offer(num);
			if(minQ.size() - maxQ.size() > 1) maxQ.offer(minQ.poll());
		}
	}
	
	public double findMedian() {
		if(maxQ.size() != minQ.size()) return (double)minQ.peek();
		else return (minQ.peek() + maxQ.peek()) / 2.0D;
	}
}

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

Reference

  1. Solutions to follow-ups