当前位置:网站首页>程序员代码面试指南 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;
}
边栏推荐
- 一个往年的朋友
- Dry goods!How to Construct SRv6-TE Performance Test Environment Using Instrumentation
- Difference Between Compiled and Interpreted Languages
- Game Theory (Depu) and Sun Tzu's Art of War (42/100)
- MySQL4
- Valentine's Day Romantic 3D Photo Wall [with source code]
- typescript27 - what about enumeration types
- mysql中解决存储过程表名通过变量传递的方法
- Input输入框光标在前输入后自动跳到最后面的bug
- Make your Lottie support word wrapping in text fields
猜你喜欢
认真对待每一个时刻
IJCAI2022 | Hybrid Probabilistic Reasoning with Algebraic and Logical Constraints
Hackers can how bad to what degree?
UE4 模型OnClick事件不生效的两种原因
JS new fun(); class and instance JS is based on object language Can only act as a class by writing constructors
Input输入框光标在前输入后自动跳到最后面的bug
Simulation of Active anti-islanding-AFD Active Anti-islanding Model Based on Simulink
基于Arduino制作非接触式测温仪
Dry goods!How to Construct SRv6-TE Performance Test Environment Using Instrumentation
Interview Blitz 69: Is TCP Reliable?Why?
随机推荐
lambda
The method of solving stored procedure table name passing through variable in mysql
Basic Theoretical Knowledge of Software Testing - Use Cases
数组问题之《两数之和》以及《三数之和 》
C# | 使用Json序列化对象时忽略只读的属性
Pyspark机器学习:向量及其常用操作
Dart named parameter syntax
Mysql基础篇(Mysql数据类型)
Hackers can how bad to what degree?
typescript28-枚举类型的值以及数据枚举
Valentine's Day Romantic 3D Photo Wall [with source code]
使用ts-node报错
The kernel's handling of the device tree
Simple and easy to use task queue - beanstalkd
数组问题之《下一个排列》、《旋转图像》以及二分查找之《搜索二维矩阵》
typescript28 - value of enumeration type and data enumeration
MLP neural network, GRNN neural network, SVM neural network and deep learning neural network compare and identify human health and non-health data
In the shake database, I want to synchronize the data of the source db0 to the destination db5, how to set the parameters?
2. # code comments
PMP 项目质量管理