Skip to content

Commit ddfa663

Browse files
authored
Create sliding-window-median.py
1 parent 4831c0f commit ddfa663

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

Python/sliding-window-median.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# Time: O(nlogk)
2+
# Space: O(n)
3+
4+
import collections
5+
import heapq
6+
7+
8+
class Solution(object):
9+
def medianSlidingWindow(self, nums, k):
10+
"""
11+
:type nums: List[int]
12+
:type k: int
13+
:rtype: List[float]
14+
"""
15+
min_heap, max_heap = [], []
16+
for i in xrange(k):
17+
if k%2:
18+
heapq.heappush(min_heap, -heapq.heappushpop(max_heap, -nums[i]))
19+
else:
20+
heapq.heappush(max_heap, -heapq.heappushpop(min_heap, nums[i]))
21+
result = [float(min_heap[0])] if k%2 else [(min_heap[0]-max_heap[0])/2.0]
22+
to_remove = collections.defaultdict(int)
23+
for i in xrange(k, len(nums)):
24+
heapq.heappush(max_heap, -heapq.heappushpop(min_heap, nums[i]))
25+
if nums[i-k] > -max_heap[0]:
26+
heapq.heappush(min_heap, -heapq.heappop(max_heap))
27+
to_remove[nums[i-k]] += 1
28+
while max_heap and -max_heap[0] in to_remove: # lazy delete
29+
to_remove[-max_heap[0]] -= 1
30+
if not to_remove[-max_heap[0]]:
31+
del to_remove[-max_heap[0]]
32+
heapq.heappop(max_heap)
33+
while min_heap[0] in to_remove:
34+
to_remove[min_heap[0]] -= 1
35+
if not to_remove[min_heap[0]]:
36+
del to_remove[min_heap[0]]
37+
heapq.heappop(min_heap)
38+
if k%2:
39+
result.append(float(min_heap[0]))
40+
else:
41+
result.append((min_heap[0]+(-max_heap[0]))/2.0)
42+
return result

0 commit comments

Comments
 (0)