The median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle values.
For examples, if arr = [2,3,4], the median is 3.
For examples, if arr = [1,2,3,4], the median is (2 + 3) / 2 = 2.5.
You are given an integer array nums and an integer k. There is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position.
Return the median array for each window in the original array. Answers within 10-5 of the actual value will be accepted.
Input:
nums =[1,3,-1,-3,5,3,6,7], k =3Output:
[1.00000,-1.00000,-1.00000,3.00000,5.00000,6.00000]Explanation:
Window position Median
--------------------[13-1]-3536711[3-1-3]5367-113[-1-35]367-113-1[-353]67313-1-3[536]7513-1-35[367]6
Example 2:
1
2
3
4
Input:
nums =[1,2,3,4,2,3,1,4,2], k =3Output:
[2.00000,3.00000,3.00000,3.00000,2.00000,3.00000,2.00000]
The key idea is to maintain two heaps: a max-heap for the smaller half of the window and a min-heap for the larger half. This allows efficient retrieval of the median at each step. As the window slides, we add the new element and remove the outgoing one, rebalancing the heaps as needed.
from collections import defaultdict
from heapq import heappush, heappop, heappushpop
from typing import List
classSolution:
defmedianSlidingWindow(self, nums: List[int], k: int) -> List[float]:
small, large = [], []
delayed = defaultdict(int)
ans = []
defprune(heap):
while heap and delayed[heap[0][1] if heap is large else-heap[0][1]]:
num = heap[0][1] if heap is large else-heap[0][1]
delayed[num] -=1 heappop(heap)
defbalance():
if len(small) > len(large) +1:
heappush(large, (-small[0][0], -small[0][1]))
heappop(small)
prune(small)
elif len(large) > len(small):
heappush(small, (-large[0][0], -large[0][1]))
heappop(large)
prune(large)
for i, num in enumerate(nums):
ifnot small or num <=-small[0][0]:
heappush(small, (-num, -num))
else:
heappush(large, (num, num))
if i >= k:
out_num = nums[i - k]
delayed[out_num] +=1if out_num <=-small[0][0]:
prune(small)
else:
prune(large)
balance()
if i >= k -1:
if k %2:
ans.append(float(-small[0][0]))
else:
ans.append((-small[0][0] + large[0][0]) /2)
return ans