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.
arr = [2,3,4], the median is 3.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 = 3
Output: [1.00000,-1.00000,-1.00000,3.00000,5.00000,6.00000]
Explanation:
Window position Median
--------------- -----
[1 3 -1] -3 5 3 6 7 1
1 [3 -1 -3] 5 3 6 7 -1
1 3 [-1 -3 5] 3 6 7 -1
1 3 -1 [-3 5 3] 6 7 3
1 3 -1 -3 [5 3 6] 7 5
1 3 -1 -3 5 [3 6 7] 6
Input: nums = [1,2,3,4,2,3,1,4,2], k = 3
Output: [2.00000,3.00000,3.00000,3.00000,2.00000,3.00000,2.00000]
The brute force approach involves recalculating the median every time the sliding window moves. For each new window, we sort the window elements and directly compute the median. This approach is straightforward but inefficient, as sorting each time takes considerable time.
nums array, from the start to the end minus the window size k.k and sort it.k is odd, the median is the middle element of the sorted window.k is even, the median is the average of the two middle elements.We can use two heaps to maintain the order of the sliding window:
By always maintaining balance between the two heaps, the median can be derived efficiently:
PriorityQueue for both heaps.