当前位置:网站首页>滑动窗口的最大值
滑动窗口的最大值
2022-08-03 12:47:00 【Array_new】
滑动窗口的最大值
给定一个数组 nums 和滑动窗口的大小 k,请找出所有滑动窗口里的最大值。
示例:
输入: nums = [1,3,-1,-3,5,3,6,7], 和 k = 3
输出: [3,3,5,5,6,7]
解释:
滑动窗口的位置 最大值
[1 3 -1] -3 5 3 6 7 3
1 [3 -1 -3] 5 3 6 7 3
1 3 [-1 -3 5] 3 6 7 5
1 3 -1 [-3 5 3] 6 7 5
1 3 -1 -3 [5 3 6] 7 6
1 3 -1 -3 5 [3 6 7] 7
提示:
你可以假设 k 总是有效的,在输入数组不为空的情况下,1 ≤ k ≤ 输入数组的大小。
class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
if(nums.length==0)return nums;
int[] a=new int[k];
int[] end=new int[nums.length-k+1];
int j=0;
int cur=0;
for(int i=0;i<nums.length;i++){
a[j]=nums[i];
j++;
if(j==k){
Arrays.sort(a);
end[cur]=a[k-1];
i=cur;
cur++;
j=0;
}
if(i==nums.length+1)break;
}
return end;
}
}
本题可以利用数组和指针来求解,先声明cur
这个指针指向滑动窗口的第一个值由于循环的+
是在循环后执行所以用该指向的位置减去1
就可以得到新的数组,利用Arrays
种的sort
方法找出最大值,这样就可以利用简单的for循环来求解答案,存放在最终的数组中,同样也可以利用队列或栈来求解来减少时间复杂度。
边栏推荐
猜你喜欢
B站回应“HR 称核心用户都是 Loser”:该面试官去年底已被劝退,会吸取教训加强管理
An introduction to the skeleton tool
Real number rounding and writing to file (C language file)
基于php志愿者服务平台管理系统获取(php毕业设计)
An动画基础之元件的影片剪辑动画与传统补间
特征降维学习笔记(pca和lda)(1)
ECCV 2022 | AirDet: 无需微调的小样本目标检测方法
An动画基础之按钮动画与基础代码相结合
Image fusion SDDGAN article learning
leetcode16最接近的三数之和 (排序+ 双指针)
随机推荐
【R】用grafify搞定统计绘图、方差分析、干预比较等!
How to disable software from running in the background in Windows 11?How to prevent apps from running in the background in Windows 11
The new interface, jingdong comment interface
Redis连接池工具类
汉源高科G8032标准ERPS环网交换机千兆4光10电工业以太网交换机环网+WEB管理+SNMP划VLAN
GameFi industry down but not out | June Report
浅谈程序员的职业操守
(through page) ali time to upload the jar
SQL分页查询_Sql根据某个字段分页
链游NFT元宇宙游戏系统开发技术方案及源码
秋招招工作
Redis connection pool tool class
无监督学习KMeans学习笔记和实例
R language ggplot2 visualization: use the patchwork bag plot_layout function will be more visual image together, ncol parameter specifies the number of rows, specify byrow parameters configuration dia
An动画优化之传统引导层动画
Byte's favorite puzzle questions, how many do you know?
IDEA的模板(Templates)
一些测试相关知识
安防监控必备的基础知识「建议收藏」
Basic principle of the bulk of the animation and shape the An animation tip point