Skip to content

Commit 27e7a81

Browse files
authored
Update sliding-window-median.py
1 parent c783023 commit 27e7a81

File tree

1 file changed

+26
-6
lines changed

1 file changed

+26
-6
lines changed

Python/sliding-window-median.py

Lines changed: 26 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,34 @@
1+
# Time: O(nlogk)
2+
# Space: O(k)
3+
4+
from sortedcontainers import SortedList
5+
6+
7+
class Solution(object):
8+
def medianSlidingWindow(self, nums, k):
9+
"""
10+
:type nums: List[int]
11+
:type k: int
12+
:rtype: List[float]
13+
"""
14+
sl = SortedList()
15+
for i in xrange(k):
16+
sl.add(float(nums[i]))
17+
result = [(sl[k//2]+sl[k//2-(1-k%2)])/2]
18+
for i in xrange(k, len(nums)):
19+
sl.add(float(nums[i]))
20+
del sl[sl.bisect_left(nums[i-k])]
21+
result.append((sl[k//2]+sl[k//2-(1-k%2)])/2)
22+
return result
23+
24+
125
# Time: O(nlogn) due to lazy delete
226
# Space: O(n)
3-
427
import collections
528
import heapq
629

730

8-
class Solution(object):
31+
class Solution2(object):
932
def medianSlidingWindow(self, nums, k):
1033
"""
1134
:type nums: List[int]
@@ -35,8 +58,5 @@ def medianSlidingWindow(self, nums, k):
3558
if not to_remove[min_heap[0]]:
3659
del to_remove[min_heap[0]]
3760
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)
61+
result.append(float(min_heap[0]) if k%2 else (min_heap[0]-max_heap[0])/2.0)
4262
return result

0 commit comments

Comments
 (0)