2015年11月5日星期四

Leetcode 295 Find Median from Data Stream

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.
Examples: 
[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.
For example:
add(1)
add(2)
findMedian() -> 1.5
add(3) 
findMedian() -> 2
Solution 1: Use BST with size of sub-tree in the node will solve the question. add and find operation will be O(logn) complexity.
 class MedianFinder {  
   public class TreeNode {  
     private int val;  
     private int size;  
     private TreeNode left, right;  
     public TreeNode(int num) {  
       val=num;  
       size=1;  
     }  
   }  
   private TreeNode root=null;  
   // Adds a number into the data structure.  
   public void addNum(int num) {  
     root=addNum(root, num);  
   }  
   private TreeNode addNum(TreeNode x, int num) {  
     if (x==null) return new TreeNode(num);  
     x.size++;  
     if (num>x.val) x.right=addNum(x.right,num);  
     if (num<x.val) x.left=addNum(x.left,num);  
     return x;  
   }  
   // Returns the median of current data stream  
   public double findMedian() {  
     int n=root.size;  
     if (n%2==1) return find(root,n/2+1);  
     return (double)(find(root,n/2)+find(root,n/2+1))/2;  
   }  
   private int find(TreeNode x, int k) {  
     if (size(x.left)>=k) return find(x.left,k);  
     if (x.size-size(x.right)<k) return find(x.right,k-x.size+x.right.size);  
     return x.val;  
   }  
   private int size(TreeNode x) {  
     if (x==null) return 0;  
     return x.size;  
   }  
 }  

没有评论:

发表评论