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

    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].

    解决思路

    1. 最直观的方法就是逐个比较,时间复杂度为O(kn);

    2. 另一种更加巧妙的方法是借助一个双向队列,滑窗的同时记录下当前窗口的最大值。

    具体做法为

    1. 输入元素的个数不足k时,进队列;

    2. 否则,比较当前元素和队列尾部的元素,如果队列尾部的元素小于当前元素则不断地将队尾元素出队;

    3. 每次记录下队列的头元素为滑动窗口中的最大元素,并且需要判断该最大元素是否为窗口的首元素,如果是则需要移除。

    程序

    public class Solution {
        public int[] maxSlidingWindow(int[] nums, int k) {
    		if (nums == null || nums.length == 0 || nums.length < k) {
    			return new int[0];
    		}
    
    		LinkedList<Integer> doublyQueue = new LinkedList<Integer>();
    		int[] maxs = new int[nums.length - k + 1];
    for (int i = 0; i < nums.length; i++) { while (!doublyQueue.isEmpty() && doublyQueue.getLast() < nums[i]) { doublyQueue.removeLast(); } doublyQueue.add(nums[i]); if (i < k - 1) { continue; } maxs[i - k + 1] = doublyQueue.getFirst(); if (doublyQueue.getFirst() == nums[i - k + 1]) { doublyQueue.removeFirst(); } } return maxs; } }
  • 相关阅读:
    对于js中原型的理解
    换行问题
    居中方法
    浮动清除
    js基础内容 原型与实例
    uniapp 吸顶 小demo
    uniapp 锚点滚动报错(h.push is not a function)
    uni-app 页面滚动到指定位置
    过滤后端返回的html文本标签
    uniapp 上拉加载
  • 原文地址:https://www.cnblogs.com/harrygogo/p/4658317.html
Copyright © 2011-2022 走看看