当前位置:网站首页>【剑指 Offer】59 - I. 滑动窗口的最大值
【剑指 Offer】59 - I. 滑动窗口的最大值
2022-07-07 16:36:00 【LuZhouShiLi】
剑指 Offer 59 - I. 滑动窗口的最大值
题目
给定一个数组 nums 和滑动窗口的大小 k,请找出所有滑动窗口里的最大值。
思路
- 遍历给定数组中的元素,如果队列不为空且当前考察的元素大于等于队尾元素,则将队尾元素移除,直到队列为空或者当前考察元素小于新的队尾元素
- 当队首元素的下标小于滑动窗口的左侧边界Left表示队首元素已经不再属于滑动窗口,将其从队首元素移除
- 由于数组下标从0开始,因此当窗口的右边界right + 1>= k,意味着窗口已经形成。此时队首元素就是该窗口内的最大值。
代码
class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
if(nums.length == 0)
{
return new int[0];
}
// 窗口个数
int[] res = new int[nums.length - k + 1];
LinkedList<Integer> queue = new LinkedList<>();
// 遍历数组中元素, right表示滑动窗口右边界
for(int right = 0; right < nums.length; right++)
{
// 如果队列不为空 并且当前的元素大于或者等于队尾元素 将队尾元素移除
// 直到 队列为空 或者当前的元素小于新的队尾元素
while(!queue.isEmpty() && nums[right] >= nums[queue.peekLast()]){
queue.removeLast();
}
// 存储元素下标
queue.addLast(right);
// 计算窗口左侧边界
int left = right - k + 1;
//当队首元素的下标小于滑动窗口左侧边界Left
// 表示队首元素已经不再滑动窗口内部 将其从队首中移除
if(queue.peekFirst() < left)
{
queue.removeFirst();
}
// 下边从0开始 所以当right + 1 >= k 说明滑动窗口已经形成 队首元素就是窗口的最大值
if(right + 1 >= k)
{
res[left] = nums[queue.peekFirst()];// 将队首元素存储到res中
}
}
return res;
}
}
边栏推荐
- What are the financial products in 2022? What are suitable for beginners?
- Yearning-SQL审核平台
- Native JS verification code
- idea彻底卸载安装及配置笔记
- Machine vision (1) - Overview
- 2021年全国平均工资出炉,你达标了吗?
- Five network IO models
- List selection JS effect with animation
- Hutool - 轻量级 DB 操作解决方案
- What is the general yield of financial products in 2022?
猜你喜欢
线程池和单例模式以及文件操作
Download, installation and development environment construction of "harmonyos" deveco
2021年全国平均工资出炉,你达标了吗?
上市十天就下线过万台,欧尚Z6产品实力备受点赞
Explain it in simple terms. CNN convolutional neural network
CVPR 2022丨学习用于小样本语义分割的非目标知识
Classification of regression tests
Test for 3 months, successful entry "byte", my interview experience summary
idea彻底卸载安装及配置笔记
嵌入式C语言程序调试和宏使用的技巧
随机推荐
Tips for this week 131: special member functions and ` = Default`
[principles and technologies of network attack and Defense] Chapter 3: network reconnaissance technology
Tear the Nacos source code by hand (tear the client source code first)
Discuss | frankly, why is it difficult to implement industrial AR applications?
海量数据去重的hash,bitmap与布隆过滤器Bloom Filter
回归测试的分类
行业案例|数字化经营底座助力寿险行业转型
Skills of embedded C language program debugging and macro use
SQLite SQL exception near "with": syntax error
debian10系统问题总结
CVPR 2022丨学习用于小样本语义分割的非目标知识
[principle and technology of network attack and Defense] Chapter 6: Trojan horse
直播软件搭建,canvas文字加粗
云景网络科技面试题【杭州多测师】【杭州多测师_王sir】
Wireshark analyzes packet capture data * cap
Wireshark分析抓包数据*.cap
Disk storage chain B-tree and b+ tree
The report of the state of world food security and nutrition was released: the number of hungry people in the world increased to 828million in 2021
性能测试过程和计划
Taffydb open source JS database