用bisect维护即可
class Solution:
def medianSlidingWindow(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[float]
"""
import bisect
n=len(nums)
res=[]
tmp=sorted(nums[:k])
res.append(self.get(tmp)*1.0)
for i in range(n-k):
index=bisect.bisect_left(tmp,nums[i])
del tmp[index]
bisect.insort(tmp,nums[i+k])
res.append(self.get(tmp)*1.0)
return res
def get(self,tmp):
l=len(tmp)
if l&1==1: return tmp[l//2]
else: return tmp[l//2-1]*0.5+tmp[l//2]*0.5