We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
1) Started sorting the input list.
2) Iterated over the input list starting from the last element and decreasing the iterator. In each step of this loop, calculate the median of the sorted list and remove the last element of the non sorted original input list from the sorted list (using binary search to locate the element).
3) Reversed the result list.
Code:
public static List<Double> runningMedian(List<Integer> a) {
var results = new ArrayList<Double>();
var c = List.copyOf(a);
Collections.sort(a);
for (int k = a.size(); k > 0; k--) {
if (k % 2 == 0) {
results.add(((double) a.get(k / 2) + a.get((k / 2) - 1)) / 2.0);
} else {
results.add((double) a.get(k / 2));
}
a.remove(Collections.binarySearch(a, c.get(k - 1)));
}
Collections.reverse(results);
return results;
}
Cookie support is required to access HackerRank
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 →
My short solution, passes all tests. Steps:
1) Started sorting the input list.
2) Iterated over the input list starting from the last element and decreasing the iterator. In each step of this loop, calculate the median of the sorted list and remove the last element of the non sorted original input list from the sorted list (using binary search to locate the element). 3) Reversed the result list.
Code:
public static List<Double> runningMedian(List<Integer> a) {