当前位置:网站首页>Leetcode:剑指 Offer 59 - I. 滑动窗口的最大值
Leetcode:剑指 Offer 59 - I. 滑动窗口的最大值
2022-07-01 03:16:00 【Re:fused】
题目:剑指 Offer 59 - I. 滑动窗口的最大值
题意:
给定一个数组 nums 和滑动窗口的大小 k,请找出所有滑动窗口里的最大值。
思路:
采取优先队列,队首为大的元素,有限队列中存入两个数据,数值和位置,首先把前k个数据放入,在窗口进行滑动时,加入新的元素,查看队首最大的元素是不是当前窗口,不是则弹出,知道是当前窗口为止。
代码:
class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
priority_queue<pair<int, int>>q;
vector<int>temp;
if(nums.size() == 0)return temp;
for(int i = 0; i < k; i++){
q.emplace(nums[i], i);
}
vector<int>ans = {
q.top().first};
for(int i = k; i < nums.size(); i++){
q.emplace(nums[i], i);
while(q.top().second <= i-k)q.pop();
ans.push_back(q.top().first);
}
return ans;
}
};
边栏推荐
- Introduction to webrtc concept -- an article on understanding source, track, sink and mediastream
- Include() of array
- split(),splice(),slice()傻傻分不清楚?
- ctfshow爆破wp
- [nine day training] content III of the problem solution of leetcode question brushing Report
- C language EXECL function
- Pytest -- plug-in writing
- 不用加减乘除实现加法
- pytorch nn.AdaptiveAvgPool2d(1)
- How to verify whether the contents of two files are the same
猜你喜欢
随机推荐
Nacos
About the application of MySQL
Introduction to EtherCAT
split(),splice(),slice()傻傻分不清楚?
Keil5中如何做到 0 Error(s), 0 Warning(s).
Force buckle - sum of two numbers
网页不能右键 F12 查看源代码解决方案
C language EXECL function
Feign remote call and getaway gateway
4、【WebGIS实战】软件操作篇——数据导入及处理
Include() of array
LeetCode 144二叉树的前序遍历、LeetCode 114二叉树展开为链表
Learning notes for introduction to C language multithreaded programming
实战 ELK 优雅管理服务器日志
数据库中COMMENT关键字的使用
Mysql知识点
shell脚本使用两个横杠接收外部参数
Cookie&Session
Ultimate dolls 2.0 | encapsulation of cloud native delivery
C语言多线程编程入门学习笔记