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 value.
Examples:
[2,3,4]
, the median is 3
[2,3]
, the median is (2 + 3) / 2 = 2.5
Given an array nums, 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. Your job is to output the median array for each window in the original array.
For example,
Given nums = [1,3,-1,-3,5,3,6,7]
, and k = 3.
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
Therefore, return the median sliding window as [1,-1,-1,3,5,6]
.
Note:
You may assume k
is always valid, ie: k
is always smaller than input array's size for non-empty array.
Answers within 10^-5
of the actual value will be accepted as correct.
-------------------------------
简化代码思路,包函数
bug1: 两个堆用同一个dic
bug2:调整完没有clear_top
class Solution:
def medianSlidingWindow(self, nums: List[int], k: int) -> List[float]:
def clear_top(pq, drop_dic, is_min_heap):
while (pq and drop_dic[pq[0] if is_min_heap else -pq[0]] > 0):
item = heapq.heappop(pq) if is_min_heap else -heapq.heappop(pq)
drop_dic[item] -= 1
def pop_item(pq, drop_dic, is_min_heap):
if pq:
res = heapq.heappop(pq) if is_min_heap else -heapq.heappop(pq)
clear_top(pq, drop_dic, is_min_heap)
return res
def push_item(item, pq, drop_dic, is_min_heap):
element = item if is_min_heap else -item
heapq.heappush(pq, element)
clear_top(pq, drop_dic, is_min_heap)
max_heap, min_heap, max_dic, min_dic, res = [], [], defaultdict(int), defaultdict(int), []
max_cnt, min_cnt, l = 0, 0, len(nums)
for i in range(l):
if (i >= k):
if (nums[i-k] >= min_heap[0]):
min_cnt,min_dic[nums[i-k]] = min_cnt-1,min_dic[nums[i-k]]+1
clear_top(min_heap, min_dic, True)
else:
max_cnt,max_dic[nums[i-k]] = max_cnt-1,max_dic[nums[i-k]]+1
clear_top(max_heap, max_dic, False)
push_item(nums[i], min_heap, min_dic, True)
min_heap_top = pop_item(min_heap, min_dic, True)
push_item(min_heap_top, max_heap, max_dic, False)
max_cnt += 1
if (max_cnt > min_cnt):
max_heap_top = pop_item(max_heap, max_dic, False)
push_item(max_heap_top, min_heap, min_dic, True)
max_cnt, min_cnt = max_cnt-1, min_cnt+1
if (i >= k - 1):
res.append((min_heap[0] - max_heap[0]) / 2.0 if k % 2 == 0 else min_heap[0])
return res