Learn Python from a baby! Record the questions in the Blue Bridge Cup Python learning and test preparation process, and record every moment.
Attached is a summary post: Pupils Blue Bridge Cup Python Breakthrough | Summary_COCOgsta's Blog-CSDN Blog
【Description】
Given an array of length n and a sliding window of size m (0<m≤n), please find the maximum value in all sliding windows.
For example, the array {2,6,4,9,8,5,5,2}, the size of the sliding window is 3, then there are 6 sliding windows, and their maximum values are 6,9,9,9, 8,5.
【Code Explanation】
a = [0,2,6,4,9,8,5,5,2]
m = 3
for i in range(m, len(a)):
mx = a[i]
for j in range(i-m+1, i+1):
mx = max(mx, a[j])
print(mx)
复制代码
#单调队列
a = [0,2,6,4,9,8,5,5,2]
q = [0,1,2,3,4,5,6,7,8]
m = 3
h = 0
t = -1
for i in range(1, len(a)):
#q[h]不在窗口[i-m+1]内,队头出队
if h<=t and q[h]<i-m+1:
h += 1
#当前值>=队尾值,队尾出队
while h<=t and a[i]>=a[q[t]]:
t -= 1
#下标入队,便于队头出队
t+=1
q[t] = i
#使用队头最大值
if i > m - 1: #满3个时才输出
print(a[q[h]])
复制代码
【operation result】
6
9
9
9
8
5