|
| 1 | +# 480. Sliding Window Median |
| 2 | + |
| 3 | +## Sort Solution |
| 4 | +- Run-time: O(N*K) |
| 5 | +- Space: O(K) |
| 6 | +- N = Number of elements in nums |
| 7 | +- K = Given k value |
| 8 | + |
| 9 | +Similar to question 295. |
| 10 | + |
| 11 | +By keeping a sorted array of size K, we can use binary search for each new number at O(logK) run-time. |
| 12 | +However, due to the requirement of the sliding window, we need to find the previous value that is outside of the sliding window and remove it from the sorted array. This takes O(logK) with binary search to find but O(K) to rebuild the array after deletion. |
| 13 | +We would then have to do this N times, therefore O(N*K) overall run-time. |
| 14 | + |
| 15 | +``` |
| 16 | +import bisect |
| 17 | +
|
| 18 | +class Solution: |
| 19 | + def medianSlidingWindow(self, nums: List[int], k: int) -> List[float]: |
| 20 | + window, results = list(), list() |
| 21 | + median_idx = k // 2 |
| 22 | + for idx, n in enumerate(nums): |
| 23 | + bisect.insort(window, n) |
| 24 | + if len(window) > k: |
| 25 | + window.pop(bisect.bisect_left(window, nums[idx-k])) |
| 26 | + if len(window) == k: |
| 27 | + results.append(window[median_idx] if k % 2 \ |
| 28 | + else (window[median_idx-1] + window[median_idx]) / 2) |
| 29 | + return results |
| 30 | +``` |
| 31 | + |
| 32 | +Slightly better performance but same big O run-time. |
| 33 | +``` |
| 34 | +import bisect |
| 35 | +
|
| 36 | +class Solution: |
| 37 | + def medianSlidingWindow(self, nums: List[int], k: int) -> List[float]: |
| 38 | + window, results = list(nums[0:k-1]), list() |
| 39 | + window.sort() |
| 40 | + median_idx = k // 2 |
| 41 | + for idx, n in enumerate(nums[k-1:], k-1): |
| 42 | + bisect.insort(window, n) |
| 43 | + results.append(window[median_idx] if k % 2 \ |
| 44 | + else (window[median_idx-1] + window[median_idx]) / 2) |
| 45 | + window.pop(bisect.bisect_left(window, nums[idx-k+1])) |
| 46 | + return results |
| 47 | +``` |
0 commit comments