Find the Running Median

  • + 0 comments

    Java O(nlogn)

    public static List<Double> runningMedian(List<Integer> a) {
                List<Double> medians = new ArrayList<>();
                PriorityQueue<Integer> lower = new PriorityQueue<>(Collections.reverseOrder());
                PriorityQueue<Integer> upper = new PriorityQueue<>();
    
                for (int num : a) {
                    if (lower.isEmpty() || num <= lower.peek()) {
                        lower.offer(num);
                    } else {
                        upper.offer(num);
                    }
    
                    if (lower.size() > upper.size() + 1) {
                        upper.offer(lower.poll());
                    } else if (upper.size() > lower.size()) {
                        lower.offer(upper.poll());
                    }
    
                    if (lower.size() == upper.size()) {
                        medians.add((lower.peek() + upper.peek()) / 2.0);
                    } else {
                        medians.add((double) lower.peek());
                    }
                }
                return medians;
            }