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;
        }
    }
  • 相关阅读:
    比SRCNN效果好的传统超分辨率算法汇总
    CSS3 2D转换
    CSS3 文本效果
    CSS3 Gradients(渐变)
    CSS3 背景
    CSS3 圆角
    CSS3 边框
    CSS3 简介
    CSS 属性选择器
    CSS 媒体类型
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12701119.html
Copyright © 2011-2022 走看看