Leetcode239. Maximum sliding window

Title Description

Given an array nums, have a size of k rightmost sliding window moves from the leftmost array to array. You can only see k digits in the sliding window. A time sliding window moves to the right one.

Returns the maximum value in the sliding window.

Example:

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

Position of the sliding window maximum
--------------- -----
[-1. 3. 1] -3. 5. 6. 3 max. 7:. 3
. 1 [. 3 -3 -1]. 5 max. 6. 7. 3:. 3
. 1. 3 [-3 -1. 5]. 3 max. 6. 7:. 5
. 1. 3 -1 [-3. 3. 5] max. 6. 7:. 5
. 1. 3 -1 -3 [. 3. 5. 6] max. 7: . 6
. 1. 5. 3 -3 -1 [. 3. 6. 7] max:. 7

answer

The main question is used to study a classic title deque and dynamic programming. Temporarily first solution deque impress. After moving to do supplementary regulations (?)

Violence (java)

Ideas: as follows.


class Solution {
    public int[] maxSlidingWindow(int[] nums, int k) {
        if (nums.length == 0 || k == 0) return new int[0];
        int[] ans = new int[nums.length - k + 1];
        int[] tmp = new int[k];
        for ( int i = 0; i < nums.length - k + 1; i++) {
            // 更新tmp
            int index = 0; 
            for ( int j = i; j < i + k; j ++) {
                tmp[index++] = nums[j]; 
            }
            // 找tmp里的最大值
            Arrays.sort(tmp);
            // 将最大值保存在ans里
            ans[i] = tmp[k-1];
        } 
        return ans;
    }
}

Complexity Analysis

  • Time complexity: O ( n k n * k )
  • Space complexity: O (n)

Deque (java)

Thought: deque data structure i.e. on both sides can be directly operated. Deque most common place is to achieve a dynamic window length, or continuum, and the dynamic window has such a data structure used in a lot of problems in the.

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];
        // 遍历nums数组
        for(int i = 0;i < nums.length;i++){
            // 保证从大到小 如果前面数小则需要依次弹出,直至满足要求
            while(!queue.isEmpty() && nums[queue.peekLast()] <= nums[i]){
                queue.pollLast();
            }
            // 添加当前值对应的数组下标
            queue.addLast(i);
            // 判断当前队列中队首的值是否有效
            if(queue.peek() <= i-k){
                queue.poll();   
            } 
            // 当窗口长度为k时 保存当前窗口中最大值
            if(i+1 >= k){
                result[i+1-k] = nums[queue.peek()];
            }
        }
        return result;
    }
}
  • Time complexity: O (n)
  • Space complexity: O (n)
Published 43 original articles · won praise 20 · views 1452

Guess you like

Origin blog.csdn.net/Chen_2018k/article/details/104665759