当前位置:网站首页>Leetcode 239. 滑动窗口最大值
Leetcode 239. 滑动窗口最大值
2022-07-17 15:36:00 【LuZhouShiLi】
Leetcode 239. 滑动窗口最大值
题目
给你一个整数数组 nums,有一个大小为 k 的滑动窗口从数组的最左侧移动到数组的最右侧。你只可以看到在滑动窗口内的 k 个数字。滑动窗口每次只向右移动一位。返回 滑动窗口中的最大值 。
思路
参考题解:https://leetcode.cn/problems/sliding-window-maximum/solution/tu-jie-suan-fa-dan-diao-dui-lie-zui-jian-h012/
代码
class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
deque<int> q;// 双端队列
vector<int>res;
for(int i = 0; i < nums.size(); i++)
{
while(q.size() && i - k + 1 > q.front())
{
q.pop_front();// 判断对头是否在滑动窗口范围之内
}
while(q.size() && nums[i] >= nums[q.back()])
{
// 当前元素大于队尾元素
q.pop_back();// 维护单调递减队列
}
q.push_back(i);// 将当前元素插入队尾
if(i >= k - 1)
{
res.push_back(nums[q.front()]);// 滑动窗口的元素达到了k个 将队头元素插入结果数组中
}
}
return res;
}
};
边栏推荐
- 【无标题】cv 学习1转换
- 赋能城市“规、建、运、管、服”——MapGIS CIM平台探索“CIM+”多场景应用
- Wi Fi sensing technology and practice based on channel state information
- Solution of connecting MySQL instance with public network
- STL string input / output overload 1
- Leetcode 1310. Subarray XOR query
- The basic establishment of the sequence table and the related operations of adding, deleting, modifying and querying (the sequence table described in C language)
- How to delay loading JS
- Genesis与BlueRun Ventures展开深度交流
- Nintendo patent shows that the follow-up products of fitness ring accessories may be under development
猜你喜欢

解决:code ERESOLVE:ERESOLVE could not resolve 的报错问题

Valid bracket sequence of "Niuke | daily question"

2022 National latest fire-fighting facility operator (intermediate fire-fighting facility operator) simulation test questions and answers

Nintendo patent shows that the follow-up products of fitness ring accessories may be under development

【无标题】cv 学习1转换

Redis distributed cache redis cluster

Leetcode 1328. Destroy palindrome string (yes, solved)

Project construction depends on people, and success depends on people!

Enabling cities to "plan, build, operate, manage and serve" -- MAPGIS CIM platform explores "cim+" multi scenario applications

Docker install MySQL
随机推荐
mysql学习笔记-约束
Ten minutes from pytorch to mxnet
02-3、指针和引用的区别
TiKV 线程池性能调优
TCP拥塞控制详解 | 7. 超越TCP
Huawei firewall authentication technology
MAPGIS igserver Kyushu - expand service development under the control of localization environment
TiFlash 性能调优
STL string输入输出重载
Use native JS to realize the function of selecting all buttons, which is simple and clear
02-3、指針和引用的區別
Detailed explanation of MySQL show processlist
How to delay loading JS
Swift 二进制数据与16进制字符串的相互转换
TiKV Follower Read
02-2、缺省参数、函数重载、引用、隐式类型转换、关于报错
HCIP(8)
文件一键备份
Genesis与BlueRun Ventures展开深度交流
Baidu document translation API