Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit f35d508

Browse files
Added question 480.
1 parent e1fb8ca commit f35d508

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
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

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /