当前位置:网站首页>滑动窗口的最大值
滑动窗口的最大值
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循环来求解答案,存放在最终的数组中,同样也可以利用队列或栈来求解来减少时间复杂度。
边栏推荐
- An工具介绍之3D工具
- An工具介绍之摄像头
- An动画基础之散件动画原理与形状提示点
- 类和对象(中上)
- An动画基础之元件的影片剪辑效果
- 基于php校园医院门诊管理系统获取(php毕业设计)
- [Verilog] HDLBits Problem Solution - Circuits/Sequential Logic/Latches and Flip-Flops
- Graphic animation and button animation of an animation basic component
- Five, the function calls
- Feature dimensionality reduction study notes (pca and lda) (1)
猜你喜欢
随机推荐
IronOS, an open source system for portable soldering irons, supports a variety of portable DC, QC, PD powered soldering irons, and supports all standard functions of smart soldering irons
How can I get a city's year-round weather data for free?Precipitation, temperature, humidity, solar radiation, etc.
Yahoo!Answers - data set
【Verilog】HDLBits题解——Verification: Reading Simulations
长江商业银行面试
php microtime 封装工具类,计算接口运行时间(打断点)
An动画基础之按钮动画与基础代码相结合
利用pgsql插件PostGIS 实现地理坐标系数据转换
Random forest project combat - temperature prediction
An动画优化之补间形状与传统补间的优化
业界新标杆!阿里开源自研高并发编程核心笔记(2022最新版)
Byte's favorite puzzle questions, how many do you know?
leetcode16 Sum of the closest three numbers (sort + double pointer)
Secure Custom Web Application Login
【Verilog】HDLBits题解——Verification: Writing Testbenches
leetcode 11. 盛最多水的容器
8/2 训练日志(dp+思维+字典树)
An动画优化之传统引导层动画
五、函数的调用过程
图像融合DDcGAN学习笔记








