You are viewing a single comment's thread. Return to all 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; }
Seems like cookies are disabled on this browser, please enable them to open this website
Find the Running Median
You are viewing a single comment's thread. Return to all comments →
Java O(nlogn)