1.题目
给定一个长度为 n 的数组 nums 和滑动窗口的大小 size ,找出所有滑动窗口里数值的最大值。
例如,如果输入数组{2,3,4,2,6,2,5,1}及滑动窗口的大小3,那么一共存在6个滑动窗口,他们的最大值分别为{4,4,6,6,6,5}; 针对数组{2,3,4,2,6,2,5,1}的滑动窗口有以下6个: {[2,3,4],2,6,2,5,1}, {2,[3,4,2],6,2,5,1}, {2,3,[4,2,6],2,5,1}, {2,3,4,[2,6,2],5,1}, {2,3,4,2,[6,2,5],1}, {2,3,4,2,6,[2,5,1]}。
2.解法
2.1 题目框架
import java.util.*;
public class Solution {
public ArrayList<Integer> maxInWindows(int [] num, int size) {
}
}
2.2 解法1
自定义一个队列,队列进元素时就将小于队列内部的元素的值都移除,换句话,就是你比我小那么就都出去。然后该元素会一直待在队列里,直到自己有一天被移出。
class MyQueue{
private ArrayDeque<Integer> queue = new ArrayDeque<>();
public void push(int n ){
while (!queue.isEmpty()&&queue.peekLast()<n){
queue.pollLast();
}
queue.offerLast(n);
}
public int max(){
return queue.peekFirst();
}
public void pop(int n){
if(!queue.isEmpty()&&queue.peekFirst()==n){
queue.pollFirst();
}
}
}
一次性将窗口填满后,通过自定义的数据结构实现。
public ArrayList<Integer> maxInWindows(int [] num, int size) {
ArrayList<Integer> ans = new ArrayList<>();
MyQueue window = new MyQueue();
for(int i=0;i<num.length;i++){
if(i<size-1){
window.push(num[i]);
}
else {
window.push(num[i]);
ans.add(window.max());
window.pop(num[i-size+1]);
}
}
return ans;
}
总结
一次性将窗口填满后,通过自定义的数据结构实现。
算法系列在github上有一个开源项目,主要是本系列博客的demo代码。https://github.com/forestnlp/alg
如果您对软件开发、机器学习、深度学习有兴趣请关注本博客,将持续推出Java、软件架构、深度学习相关专栏。
您的支持是对我最大的鼓励。
本文介绍了如何使用自定义队列数据结构,解决给定数组和滑动窗口大小问题,找到每个滑动窗口内的最大值。通过实例和MyQueue类实现,适用于Java开发者学习数据结构在算法中的应用。
172万+

被折叠的 条评论
为什么被折叠?



