2022-4-28 滑动窗口

给你一个整数数组 nums,有一个大小为 k 的滑动窗口从数组的最左侧移动到数组的最右侧。你只可以看到在滑动窗口内的 k 个数字。滑动窗口每次只向右移动一位。

返回 滑动窗口中的最大值 

 1 class Solution {
 2     public int[] maxSlidingWindow(int[] nums, int k) {
 3         LinkedList<Integer> queue=new LinkedList<>();
 4         int l=0,r=0,n=nums.length;
 5         int[] ans=new int[n-k+1];
 6         while (r<n){
 7             while (!queue.isEmpty()&&queue.peekLast()<nums[r]) queue.pollLast();
 8             queue.offerLast(nums[r]);
 9             r++;
10             if (r-l<k) continue;
11             ans[l]=queue.peekFirst();
12             if (nums[l]==queue.peekFirst()) queue.pollFirst();
13             l++;
14         }
15         return ans;
16     }
17 }

思路:单调队列,加入队列时,把所有较小的弹出。在缩小窗口时,看当前值是否为最大值,是直接弹出。

优先队列的remove复杂度为O(n),会超时。

posted on 2022-04-28 12:15  阿ming  阅读(30)  评论(0)    收藏  举报

导航