Created
January 17, 2019 11:59
-
-
Save kocko/2e0dd038bea14a8b26fdf73901d1d15c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Comparator; | |
import java.util.PriorityQueue; | |
import java.util.Scanner; | |
class GFG { | |
private PriorityQueue<Integer> min = new PriorityQueue<>(), max = new PriorityQueue<>(Comparator.reverseOrder()); | |
public int findRunningMedian(int a) { | |
min.add(a); | |
max.add(min.poll()); | |
if (max.size() - min.size() > 1) { | |
min.add(max.poll()); | |
} | |
return (min.size() == max.size()) ? (max.peek() + min.peek()) / 2 : min.peek(); | |
} | |
public static void main(String[] args) { | |
Scanner sc = new Scanner(System.in); | |
int n = sc.nextInt(); | |
GFG instance = new GFG(); | |
while (n-- > 0) { | |
int next = sc.nextInt(); | |
int median = instance.findRunningMedian(next); | |
System.out.println(median); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment