Sliding Window Maximum

题目链接:https://leetcode.com/problems...

这道题用deque,注意一下存的是index,因为要判断是否到最大的window值,是通过现在的index和deque第一个index的差来判断的。

public class Solution {
    public int[] maxSlidingWindow(int[] nums, int k) {
        if(nums == null || nums.length == 0 || k == 0) return new int[0];
        /* result size: nums.length - k + 1
         * deque: 1st element is the largest one, store the index !!
         * 1. poll 1st element when 1st away from current = k
         * 2. poll last element while last <= current, add current
         * 3. put the 1st element into the result if index >= k - 1
         */
         int[] result = new int[nums.length - k + 1];
         Deque<Integer> deq = new LinkedList();
         for(int i = 0; i < nums.length; i++) {
             // step 1
             if(!deq.isEmpty() && i - deq.peek() == k) deq.poll();
             // step 2
             while(!deq.isEmpty() && nums[deq.peekLast()] <= nums[i]) deq.pollLast();
             deq.offer(i);
             // step 3
             if(i - k + 1 >= 0) result[i - k + 1] = nums[deq.peek()];
         }
         return result;
    }
}

lulouch13
13 声望6 粉丝