当前位置:网站首页>Code Interview Guide for Programmers CD15 Generating an Array of Windowed Maximums
Code Interview Guide for Programmers CD15 Generating an Array of Windowed Maximums
2022-08-01 04:49:00 【Go to bed early and feel good hh】
题目链接:点击这里
首先要明确的是,The index is stored in the double-ended queue.同时,It is necessary to always ensure that the value of the array element corresponding to the index in the queue decreases gradually from the beginning to the end.
ri
Used to traverse the array sequentially from left to right a[]
,同时 ri
也是滑动窗口的最右索引.
li
是滑动窗口的最左索引,即 li = ri - w + 1
.
The steps to find the maximum value of the sliding window are as follows:
如果
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;
}
边栏推荐
- IJCAI2022 | Hybrid Probabilistic Reasoning with Algebraic and Logical Constraints
- 智芯传感输液泵压力传感器 为精准智能控制注入科技“强心剂”
- 万字逐行解析与实现Transformer,并进行德译英实战(二)
- 挑战52天背完小猪佩奇(第01天)
- (2022牛客多校四)D-Jobs (Easy Version)(三维前缀或)
- typescript21-接口和类型别名的对比
- 剑指 Offer 68 - II. 二叉树的最近公共祖先
- safari浏览器怎么导入书签
- 怀念故乡的面条
- SQL Analysis of ShardingSphere
猜你喜欢
typescript23-tuple
safari浏览器怎么导入书签
Valentine's Day Romantic 3D Photo Wall [with source code]
typescript27-枚举类型呢
(2022牛客多校四)D-Jobs (Easy Version)(三维前缀或)
typescript22-接口继承
怀念故乡的面条
【kali-信息收集】枚举——DNS枚举:DNSenum、fierce
JS new fun(); class and instance JS is based on object language Can only act as a class by writing constructors
Typescript22 - interface inheritance
随机推荐
EntityFramework saves to SQLServer decimal precision is lost
"ArchSummit: The cry of the times, technical people can hear"
MySQL实践总结-
在互联网时代,有诸多「互联网+」模式的诞生
Visual Studio提供的 Command Prompt 到底有啥用
数组问题之《下一个排列》、《旋转图像》以及二分查找之《搜索二维矩阵》
6-23漏洞利用-postgresql代码执行利用
最新 955 不加班的公司名单
PAT乙级 1002 写出这个数
ICML2022 | Deep Dive into Permutation-Sensitive Graph Neural Networks
律师解读 | 枪炮还是玫瑰?从大厂之争谈元宇宙互操作性
/etc/fstab
typescript21 - Comparison of Interfaces and Type Aliases
ModuleNotFoundError: No module named ‘tensorflow.keras‘报错信息的解决方法
C# | 使用Json序列化对象时忽略只读的属性
Message Queuing Message Storage Design (Architecture Camp Module 8 Jobs)
Lawyer Interpretation | Guns or Roses?Talking about Metaverse Interoperability from the Battle of Big Manufacturers
Pyspark机器学习:向量及其常用操作
在沈自所的半年总结
微软 Win10 照片磁贴后的又一“刺客”,谷歌 Chrome 浏览器将在新标签页展示用户照片