当前位置:网站首页>程序员代码面试指南 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;
}
边栏推荐
- MLP neural network, GRNN neural network, SVM neural network and deep learning neural network compare and identify human health and non-health data
- Unity's primary method for implementing PlanarReflection under the BuildIn rendering pipeline
- 阿叶的目标
- typescript25-类型断言
- Typescript22 - interface inheritance
- 最新 955 不加班的公司名单
- Hackers can how bad to what degree?
- UE4 rays flashed from mouse position detection
- [FPGA tutorial case 43] Image case 3 - image sobel edge extraction through verilog, auxiliary verification through MATLAB
- The difference between scheduleWithFixedDelay and scheduleAtFixedRate
猜你喜欢

认真对待每一个时刻

6-23漏洞利用-postgresql代码执行利用

typescript21 - Comparison of Interfaces and Type Aliases

基于ProXmoX VE的虚拟化家庭服务器(篇一)—ProXmoX VE 安装及基础配置

scheduleWithFixedDelay和scheduleAtFixedRate的区别

Flutter "Hello world" program code

typescript21-接口和类型别名的对比

The maximum quantity leetcode6133. Grouping (medium)

Dry goods!How to Construct SRv6-TE Performance Test Environment Using Instrumentation

律师解读 | 枪炮还是玫瑰?从大厂之争谈元宇宙互操作性
随机推荐
API Design Notes: The pimpl trick
Flutter Tutorial 02 Introduction to Flutter Desktop Program Development Tutorial Run hello world (tutorial includes source code)
August 22 Promotion Ambassador Extra Reward Rules
时时刻刻保持敬畏之心
typescript24 - type inference
PMP 项目沟通管理
解决ffmpeg使用screen-capture-recorder录屏,有屏幕缩放的情况下录不全的问题
Li Chi's work and life summary in July 2022
typescript23-元组
博客系统(完整版)
The Principle Of Percona Toolkit Nibble Algorithm
ICML2022 | Deep Dive into Permutation-Sensitive Graph Neural Networks
云服务器下载安装mongo数据库并远程连接详细图文版本(全)
Interview Blitz 69: Is TCP Reliable?Why?
Excel做题记录——整数规划优化模型
Message queue design based on mysql
Simulation of Active anti-islanding-AFD Active Anti-islanding Model Based on Simulink
最新 955 不加班的公司名单
今日睡眠质量记录68分
Software Testing Weekly (Issue 82): In fact, all those who are entangled in making choices already have the answer in their hearts, and consultation is just to get the choice that they prefer.