当前位置:网站首页>程序员代码面试指南 CD15 生成窗口最大值数组
程序员代码面试指南 CD15 生成窗口最大值数组
2022-08-01 04:38:00 【早睡身体好hh】
题目链接:点击这里
首先要明确的是,双端队列中存放的是索引。同时,要时刻保证队列中的索引对应的数组元素值从头到尾是逐渐减小的。
ri
用于从左往右依次遍历数组 a[]
,同时 ri
也是滑动窗口的最右索引。
li
是滑动窗口的最左索引,即 li = ri - w + 1
。
求滑动窗口最大值的步骤如下:
如果
a[ri] >= a[队尾]
,则不断删除队尾,直到a[队尾] > a[ri]
为止。将
ri
加入队尾。当
li < 0
的时候,意味着此时还没有出现一个完整的滑动窗口,直接跳过即可。当
li >= 0
的时候,如果队头过期,就移除队头,然后记录此时滑动窗口的最大值为a[队头]
。
#include <iostream>
#include <cstdio>
#include <deque>
using namespace std;
const int N = 1000010;
int a[N];
int main()
{
int n, w;
scanf("%d%d", &n, &w);
for (int i = 0; i < n; i++)
{
scanf("%d", &a[i]);
}
deque<int> q;
for (int ri = 0; ri < n; ri++)
{
// 如果a[ri] >= a[队尾],则不断删除队尾
while (!q.empty() && a[ri] >= a[q.back()])
{
q.pop_back();
}
// 将ri加入队尾
q.push_back(ri);
int li = ri - w + 1;
// 当li < 0的时候,意味着此时还没有出现一个完整的滑动窗口,直接跳过即可
if (li < 0)
{
continue;
}
// 如果队头过期,就移除队头
if (q.front() < li)
{
q.pop_front();
}
// 记录此时滑动窗口的最大值为a[队头]
printf("%d ", a[q.front()]);
}
return 0;
}
边栏推荐
猜你喜欢
随机推荐
RSA主要攻击方法
How to promote new products online?
开源许可证 GPL、BSD、MIT、Mozilla、Apache和LGPL的区别
leetcode6132. Make all elements in an array equal to zero (simple, weekly)
风险策略调优中重要的三步分析法
Dynamic Programming 01 Backpack
typescript21-接口和类型别名的对比
在沈自所的半年总结
typescript28 - value of enumeration type and data enumeration
What is a programming language
Advice given by experts with four years of development experience in Flutter tutorial
Make your Lottie support word wrapping in text fields
基于STM32设计的UNO卡牌游戏(双人、多人对战)
阿叶的目标
这里有110+公开的专业数据集
Interview Blitz 69: Is TCP Reliable?Why?
The Flow Of Percona Toolkit pt-table-checksum
PMP 相关方管理必背总结
【愚公系列】2022年07月 Go教学课程 024-函数
leetcode:126. Word Solitaire II