求一个整数stream的sum, avg, median

好久没更新了, 上个新题吧。 求一个整数stream的sum, avg, median。 数据不断流入, 随时求sum, avg, median

 1) consume(int value)
 
 2 million
 
 2) getSum()
 3) getAverage()
 4) getMedian()
 
 
 1
 2
 -1
 0
 getSum => 1+2-1+0
 4 
 10
 20
 -90
 getAverage = 
 
 */


import java.io.*;
import java.util.*;


 
import java.math.BigInteger;
import java.math.BigDecimal;


class Solution 
{
  private BigInteger sum = new BigInteger("0");
  private double avg = 0;
  private long n = 0;
  
  private PriorityQueue maxHeap = new PriorityQueue<>(Collections.reverseOrder());
    
  private PriorityQueue minHeap = new PriorityQueue<>();
  
  public static void main(String[] args) 
  {
      Solution o = new Solution();
    
      int[] arr = new int[]{-3,-3,3,-3,-3,-3};
    
      //int[] arr1 = new int[]{-6,-4,3,3,3,3, 7, 10};

      for(int i=0; i             
   //                 3
   //  1   
    
       if(maxHeap.isEmpty()) maxHeap.add(value); 
       else if(minHeap.isEmpty()) minHeap.add(value);
       else if(value >= minHeap.peek()) minHeap.add(value);
       else if(value <= maxHeap.peek()) maxHeap.add(value);
       
       if( minHeap.size() - maxHeap.size() > 1) {
           maxHeap.add( minHeap.remove());
       } else if( maxHeap.size() - minHeap.size() > 1) {
          minHeap.add( maxHeap.remove());
       }
  }
  
  public BigInteger getSum() {
      return sum;
  }
  
  public double getAverage() {
      System.out.println("n:" +  n );
      return avg;
  }
  
  public double getMedian() {
    
    System.out.println("minheap: " + minHeap.toString() );
                       
    System.out.println("maxheap: " + maxHeap.toString() );
    
    if(minHeap.isEmpty() && maxHeap.isEmpty()) return 0.0;
    
    if(minHeap.size() == maxHeap.size()) 
      return  (minHeap.peek() + maxHeap.peek() ) / 2.0;
    else if(minHeap.size() > maxHeap.size() ) 
      return minHeap.peek();
    else return maxHeap.peek();
  }
}


你可能感兴趣的:(求一个整数stream的sum, avg, median)