zoukankan      html  css  js  c++  java
  • [LC] 239. 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.

    Follow up:
    Could you solve it in linear time?

    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

    Solution 1: brute force O(NK)
    class Solution {
        public int[] maxSlidingWindow(int[] nums, int k) {
            int len = nums.length;
            int[] res = new int[len - k + 1];
            for (int i = 0; i < res.length; i++) {
                int tmpMax = nums[i];
                for (int j = i; j < i + k; j++) {
                    tmpMax = Math.max(tmpMax, nums[j]);
                }
                res[i] = tmpMax;
            }
            return res;
        }
    }

    Solution 2: Deque O(N)

    class Solution {
        public int[] maxSlidingWindow(int[] nums, int k) {
            int[] res = new int[nums.length - k + 1];
            Deque<Integer> deque = new LinkedList<>();
            for (int i = 0; i < nums.length; i++) {
                while (!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 >= 0) {
                    // from big to small, left to right
                    res[i - k + 1] = nums[deque.peekFirst()];
                }
            }
            return res;
        }
    }
  • 相关阅读:
    volatile关键字解析(转载)
    php
    FFT快速傅立叶变换
    高次不定方程BSGS算法
    BSGS-BabyStepGiantStep算法+拓展
    Java-数组-面向对象
    Java基础-方法(2)和数组
    Java基础-循环(2)和方法
    Java基础-循环结构
    Java基础-运算符
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12701119.html
Copyright © 2011-2022 走看看