当前位置:网站首页>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;
}
};
边栏推荐
- Cookie&Session
- 【读书笔记】《文案变现》——写出有效文案的四个黄金步骤
- EtherCAT简介
- 实现pow(x,n)函数
- Kmeans
- 如何校验两个文件内容是否相同
- 后台系统右边内容如何出现滚动条和解决双滚动条的问题
- Introduction to core functions of webrtc -- an article on understanding SDP PlanB unifiedplan (migrating from PlanB to unifiedplan)
- [小样本分割]论文解读Prior Guided Feature Enrichment Network for Few-Shot Segmentation
- So easy deploy program to server
猜你喜欢
随机推荐
md5sum操作
Introduction to core functions of webrtc -- an article on understanding SDP PlanB unifiedplan (migrating from PlanB to unifiedplan)
Include() of array
Finally in promise
[us match preparation] complete introduction to word editing formula
Latest interface automation interview questions
Edge Drawing: A combined real-time edge and segment detector 翻译
Redis 教程
LeetCode 128最长连续序列(哈希set)
The value of the second servo encoder is linked to the NC virtual axis of Beifu PLC for display
Introduction to webrtc concept -- an article on understanding source, track, sink and mediastream
Mysql知识点
JS daily development tips (continuous update)
How do I use Google Chrome 11's Upload Folder feature in my own code?
Cookie&Session
Subnet division and subnet summary
Server rendering technology JSP
EtherCAT原理概述
JS日常开发小技巧(持续更新)
Thread data sharing and security -threadlocal









