Sliding Window Maximum

题目地址:
https://leetcode.com/problems/sliding-window-maximum/#/description

题目:
Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position.
For example,
Given nums = [1,3,-1,-3,5,3,6,7], and k = 3.
Window position                Max
---------------               -----
[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
Therefore, return the max sliding window as [3,3,5,5,6,7].
Note: 
You may assume k is always valid, ie: 1 ≤ k ≤ input array's size for non-empty array.
Follow up:
Could you solve it in linear time?

解题思路:
这道题主要难度在于leaner time,所以需要用到辅助数据结构。在这里我们用到的是deque。双向队列用来存储valid的index。每次循环开始需要去除head的超出的index和tail的小于curr的index。

代码:

public int[] maxSlidingWindow(int[] nums, int k) {
    if(nums == null || nums.length < k){
        return new int[0];
    }
    int len = nums.length;
    int[] rst = new int[len - k + 1];
    int p = 0;
    Deque<Integer> deque = new ArrayDeque<>();
    for(int i = 0; i <= len - 1; i++){
        if(!deque.isEmpty() && deque.peekFirst() <= i - k){
            deque.pollFirst();
        }
        while(!deque.isEmpty() && nums[deque.peekLast()] <= nums[i]){
            deque.pollLast();
        }
        deque.offerLast(i);
        if(i >= k - 1){
            rst[p++] = nums[deque.peekFirst()];
        }
    }
    return rst;
}



Comments

Popular Posts