Skip to main content

Running median - Java 8 (HARD)

Running Median:


Image result for hackerrank logo
The median of a set of integers is the midpoint value of the data set for which an equal number of integers are less than and greater than the value. To find the median, you must first sort your set of integers in non-decreasing order, then:
  • If your set contains an odd number of elements, the median is the middle element of the sorted sample. In the sorted set  is the median.
  • If your set contains an even number of elements, the median is the average of the two middle elements of the sorted sample. In the sorted set  is the median.
Given an input stream of  integers, you must perform the following task for each  integer:
  1. Add the  integer to a running list of integers.
  2. Find the median of the updated list (i.e., for the first element through the  element).
  3. Print the list's updated median on a new line. The printed value must be a double-precision number scaled to decimal place (i.e.,  format).
Input Format
The first line contains a single integer, , denoting the number of integers in the data stream.
Each line  of the  subsequent lines contains an integer, , to be added to your list.
Constraints
Output Format
After each new integer is added to the list, print the list's updated median on a new line as a single double-precision number scaled to  decimal place (i.e.,  format).
Sample Input
6
12
4
5
3
8
7
Sample Output
12.0
8.0
5.0
4.5
5.0
6.0
Explanation
There are  integers, so we must print the new median on a new line as each integer is added to the list:






















Code:


import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {
    private static PriorityQueue<Integer> maxheap = new PriorityQueue<>(Collections.reverseOrder());//max heap
    private static PriorityQueue<Integer> minheap = new PriorityQueue<>();//min heap
    public static void main(String args[] ) throws Exception {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT */
    Scanner sc = new Scanner (System.in);
    int n = sc.nextInt();
    int []arr =  new int [n];
        for (int i=0;i<n;i++){
        arr[i]=sc.nextInt();                  
        }
    medianTracker(arr);
    }
    private static void medianTracker(int [] arr){
        for (int j=0;j<arr.length;j++){
            addNumber(arr[j]);
            System.out.println(getMedian());      
        }
      }
    private static void addNumber(int n){
        if (maxheap.size()==0){
            maxheap.add(n);
        } else if (maxheap.size()==minheap.size()){
                 if (n<minheap.peek()){
                     maxheap.add(n);
                 }else{
                     minheap.add(n);
                     maxheap.add(minheap.poll());
                 }
           }else if(maxheap.size()>minheap.size()){
            if(n>maxheap.peek()){
                minheap.add(n);
             
            }else{
                maxheap.add(n);
                minheap.add(maxheap.poll());
            }
        }
    }
    private static double getMedian() {
        if (maxheap.isEmpty()) {
            return 0;
        } else if (maxheap.size() == minheap.size()) {
            return (maxheap.peek() + minheap.peek()) / 2.0;
        } else { // maxHeap must have more elements than minHeap
            return maxheap.peek();
        }
    }
}

Comments

Popular Posts

TARUNKUMAR RAWAT:Fourier Series and Fourier Transform

Tarunkumar Rawat Fourier Series: Click here to download Tarun Rawat Fourier Series Tarunkumar Rawat Fourier Transform: Click here to download TarunRawat Fourier Transform Steps to follow: 1) Click on the above link 2) Wait for 3 secs and click on the link 3) Wait for 5 secs and click on skip ad NOTE: We do require these ads to fund the site and provide books for free. Besides these are harmless and just require 5 secs waiting and nothing else. Please be patient for 5 secs and get your desired book for FREE!  IMPORTANT: We believe that every author deserves some respect and the same should be shown towards them by purchasing the books and lauding the efforts of author. Hence we recommend to buy the book. You can buy the book for an affordable rate in given below link: Using of PDF will be at your own risk and EXTC RESOURCES IS NOT RESPONSIBLE for any consequences of the same. We provide links for book and donot endorse piracy.  

Modern Digital and Analog Communication (BP Lathi,3rd ed)

Another Analog communication book: Modern Digital and Analog Communication (BP Lathi,3rd ed) : Click here to download Modern Digital and Analog Communication (BP Lathi,3rd ed) Copyright Disclaimer: This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.

Numerical methods with MATLAB

For Numerical methods along with MATLAB the best book is: Chapra Applied Numerical Methods MATLAB Engineers Scientists 3rd edition : Click here to download Steven Chapra with MATLAB For altenate link : Click here to download Steen Chapra with MATLAB