Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- private static class P50Calculator {
- final PriorityQueue<Integer> minHeap;
- final PriorityQueue<Integer> maxHeap;
- public P50Calculator(){
- minHeap = new PriorityQueue<>(new Comparator<Integer>() {
- @Override
- public int compare(Integer num1, Integer num2) {
- return num2 - num1;
- }
- });
- maxHeap = new PriorityQueue<>();
- }
- public void addValue(int value) {
- if(minHeap.isEmpty() || value<minHeap.peek()){
- minHeap.offer(value);
- } else {
- maxHeap.offer(value);
- }
- final PriorityQueue<Integer> heap1 = minHeap.size()>=maxHeap.size() ? minHeap : maxHeap;
- final PriorityQueue<Integer> heap2 = minHeap.size()<=maxHeap.size() ? minHeap : maxHeap;
- if((heap1.size()-heap2.size())>1){
- heap2.offer(heap1.poll());
- }
- }
- public double getP50(){
- if(minHeap.size()==maxHeap.size()){
- return minHeap.size()==0 ? 0 : (minHeap.peek() + maxHeap.peek())/2.0;
- }
- return minHeap.size() > maxHeap.size() ? minHeap.peek() : maxHeap.peek();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement