239.滑动窗口最大值

460 阅读1分钟

239.滑动窗口最大值

image.png

class Solution {
    public int[] maxSlidingWindow(int[] nums, int k) {
        if(nums == null || nums.length < 2) return nums;
        LinkedList<Integer> queue = new LinkedList();//保存的是数组下标,不是元素
        int[] result = new int[nums.length - k + 1];
        for(int i = 0 ; i < nums.length ; i++){
            while(!queue.isEmpty() && nums[queue.peekLast()] <= nums[i]){
                queue.pollLast();
            }
            queue.addLast(i);
            // 队列头结点需要在[i - k + 1, i]范围内,不符合则要弹出
            while(!queue.isEmpty() && queue.peek() < i - k + 1){
                queue.poll();
            }
            if(i + 1 >= k){
                result[i+1-k] = nums[queue.peek()];
            }
        }
        return result;
    }
}