239. Sliding Window Maximum (Hard)

https://leetcode.com/problems/sliding-window-maximum/

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. Return the max sliding window.

Example:

Input: nums = [1,3,-1,-3,5,3,6,7], and k = 3
Output: [3,3,5,5,6,7] 
Explanation: 

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

Note:
You may assume k is always valid, 1 ≤ k ≤ input array's size for non-empty array.

Follow up:
Could you solve it in linear time?

Hints

Solutions

class Solution {
    public int[] maxSlidingWindow(int[] nums, int k) {
        if (nums == null || nums.length == 0) {
            return new int[0];
        }

        int len = nums.length;
        int[] rst = new int[len - k + 1];
        int index = 0;
        // Use a deque to store index
        Deque<Integer> qmax = new ArrayDeque<>();
        for (int i = 0; i < len; i++) {
            //when index equals to (i-k) remove the head of deque, because it's out of range k
            if (!qmax.isEmpty() && qmax.getFirst() == i - k) {
                qmax.removeFirst();
            }
            // remove numbers that no bigger than nums[i] in k range as they are useless
            while (!qmax.isEmpty() && nums[qmax.getLast()] <= nums[i]) {
                qmax.removeLast();
            }
            // the deque - qmax contains index...
            // the array - rst contains content...
            qmax.addLast(i);
            if (i >= k - 1) {
                rst[index++] = nums[qmax.getFirst()];
            }
        }

        return rst;
    }
}
Copyright © iovi.com 2017 all right reserved,powered by GitbookLast Modification: 2019-04-15 19:06:14

results matching ""

    No results matching ""