当前位置:网站首页>程序员代码面试指南 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;
}
边栏推荐
- Mysql中的数据类型和运算符
- FFmpeg 搭建本地屏幕录制环境
- typescript27-枚举类型呢
- Message queue MySQL table for storing message data
- typescript19-对象可选参数
- 数据比对功能调研总结
- 博客系统(完整版)
- Character encoding and floating point calculation precision loss problem
- typescript24-类型推论
- MLP neural network, GRNN neural network, SVM neural network and deep learning neural network compare and identify human health and non-health data
猜你喜欢
随机推荐
产品经理访谈 | 第五代验证码的创新与背景
API Design Notes: The pimpl trick
这里有110+公开的专业数据集
"ArchSummit: The cry of the times, technical people can hear"
PMP 项目资源管理
Risk strategy important steps of tuning method
How to promote new products online?
typescript19-对象可选参数
干货!如何使用仪表构造SRv6-TE性能测试环境
JS new fun(); class and instance JS is based on object language Can only act as a class by writing constructors
请问shake数据库中为什么读取100个collection 后,直接就退出了,不继续读了呢?
The difference between scheduleWithFixedDelay and scheduleAtFixedRate
MySQL4
API设计笔记:pimpl技巧
Four implementations of
batch insert: have you really got it? 数组问题之《两数之和》以及《三数之和 》
软件测试基础理论知识—用例篇
Unknown Bounded Array
In the shake database, I want to synchronize the data of the source db0 to the destination db5, how to set the parameters?
Summary of mobile page optimization in seconds









