Funcia
Lv.3heappriority-queue

Running Median

Memory limit
256 MB
Correctness time limit
10000 ms
Solvers
0
0

Numbers arrive in the order of nums. After each arrival report the median so far: with k numbers, the ⌈k/2⌉\lceil k/2 \rceil-th smallest (the lower middle for even k).

Examples

numsresult
[1, 5, 2, 10, -99, 7, 5][1, 1, 2, 2, 2, 2, 5]
[3, 3, 3][3, 3, 3]

Efficiency

This problem has performance tests. Judge the required time complexity from the input sizes in the constraints.

Function signature

solution(nums: int[]) → int[]

Constraints

  • 1≤1 \le nums.length ≤200,000\le 200{,}000, −109≤-10^9 \le nums[i] ≤109\le 10^9

Expected complexity

Time
O(N log N)
Space
O(N)

Examples

numsExpected
[1,5,2,10,-99,7,5][1,1,2,2,2,2,5]
[3,3,3][3,3,3]

Hint

Hint

Keep a max-heap of the lower half and a min-heap of the upper half, with the lower half equal in size or one larger; its top is the answer. Re-selecting the median from scratch each time is at least O(N2)O(N^2).

Time limits per language

LanguageEfficiency time limit
C (GCC, gnu17)200 msestimated
C++ (GCC, gnu++23)200 msderived
Python 3.131000 msderived
Java 251478 msderived
Kotlin 2.4 (JVM)1400 msestimated
C# 14 (.NET 10)1400 msestimated

Test groups

GroupWeightTestsVisibility
sample02inputs and outputs
correctness407verdict only
performance604verdict only
Loading editor…
Log in to run or submit code.

No result yet. Run or submit your code.