当前位置:网站首页>滑动窗口的最大值
滑动窗口的最大值
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循环来求解答案,存放在最终的数组中,同样也可以利用队列或栈来求解来减少时间复杂度。
边栏推荐
- Oracle is installed (system disk) and transferred from the system disk to the data disk
- Classes and Objects (lower middle)
- How does Filebeat maintain file state?
- 【Verilog】HDLBits题解——Verification: Reading Simulations
- An动画优化之补间形状与传统补间的优化
- An动画基础之元件的影片剪辑动画与传统补间
- [Verilog] HDLBits Problem Solution - Circuits/Sequential Logic/Latches and Flip-Flops
- Jmeter use
- An动画基础之按钮动画与基础代码相结合
- 期货开户中常见问题汇总
猜你喜欢

云计算服务主要安全风险及应对措施初探

An introduction to basic tools for selecting line tools (package church)

Notepad++ 安装jsonview插件

Station B responded that "HR said that core users are all Loser": the interviewer was persuaded to quit at the end of last year and will learn lessons to strengthen management

Sogou news - dataset

YOLOv5训练数据提示No labels found、with_suffix使用、yolov5训练时出现WARNING: Ignoring corrupted image and/or label

An工具介绍之摄像头

setTimeout, setInterval requestAnimationFrame

BOM系列之sessionStorage

How does Filebeat maintain file state?
随机推荐
Blog records life
【精品必知】Pod生命周期
An基本工具介绍之选择线条工具(包教会)
Comics: how do you prove that sleep does not release the lock, and wait to release lock?
AMS simulation
Unsupervised learning KMeans notes and examples
An动画基础之元件的图形动画与按钮动画
An动画基础之按钮动画与基础代码相结合
[Blue Bridge Cup Trial Question 48] Scratch Dance Machine Game Children's Programming Scratch Blue Bridge Cup Trial Question Explanation
Yahoo! Answers-数据集
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动画基础之元件的影片剪辑动画与传统补间
How to disable software from running in the background in Windows 11?How to prevent apps from running in the background in Windows 11
How does Filebeat maintain file state?
An工具介绍之形状工具及渐变变形工具
业界新标杆!阿里开源自研高并发编程核心笔记(2022最新版)
可视化图表设计Cookbook
Database basics one (MySQL) [easy to understand]
Filebeat 如何保持文件状态?
[Verilog] HDLBits Problem Solution - Verification: Writing Testbenches