-
-
Notifications
You must be signed in to change notification settings - Fork 298
/
Copy path480.py
60 lines (56 loc) · 2.04 KB
/
480.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
__________________________________________________________________________________________________
sample 120 ms submission
class Solution:
def medianSlidingWindow(self, nums: List[int], k: int) -> List[float]:
window = sorted(nums[:k])
res = []
if k % 2 == 0:
res.append((window[k // 2] + window[k // 2 - 1]) / 2)
else:
res.append(window[k // 2])
for i in range(k, len(nums)):
bisect.insort(window, nums[i])
index = bisect.bisect_left(window, nums[i - k])
window.pop(index)
if k % 2 == 0:
res.append((window[k // 2] + window[k // 2 - 1]) / 2)
else:
res.append(window[k // 2])
return res
__________________________________________________________________________________________________
sample 14492 kb submission
def sortedInsert(arr, ele):
pos = len(arr)
for i, n in enumerate(arr):
if ele < n:
pos = i
break
arr.insert(pos, ele)
def populate(nums, k):
low = 0
high = k - 1
window = sorted(nums[:k])
return low, high, window
class Solution:
def medianSlidingWindow(self, nums: List[int], k: int) -> List[float]:
low, high, window = populate(nums, k)
result = []
while high < len(nums) - 1:
if k % 2 == 1:
result.append(float(window[int(k/2)]))
else:
a = window[int(k/2)]
b = window[int(k/2) - 1]
result.append(float((a+b)/2))
window.remove(nums[low])
low += 1
high += 1
sortedInsert(window, nums[high])
if k % 2 == 1:
result.append(float(window[int(k/2)]))
else:
a = window[int(k/2)]
b = window[int(k/2) - 1]
result.append(float((a+b)/2))
return result
__________________________________________________________________________________________________