码迷,mamicode.com
首页 > Windows程序 > 详细

Sliding Window Maximum

时间:2018-11-15 01:28:57      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:from   元素   and   number   linear   ati   ber   you   last   

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?

解题思路:

这道题要求在线性时间内求解,关键就是不能每次都遍历一下这个sliding window来判断当前的最大值。感觉是要维持一个递增的数据结构,和前面Max rectangle的题目很相似。

基本思路是,维持一个双向队列。遍历数组,不断将当前元素x塞进队列尾部。

1. 当sliding window往右滑动的时候,要将左侧已经滑出窗口的元素从队列头部删除(如果它还在队列里的话)。

2. 将x塞进队列前,对队列从后往前遍历,把小于x的所有元素都弹出。

   因为此时队列内元素在array中都是在x左侧的,所以如果他们小于x,是没有希望成为sliding window内的最大元素的,所以删除。

   注意,这一步不能从deque的头部开始,因为头部的元素是最大的,很有可能已经比x大,就直接结束了。然而,后面还有小于x的元素不能被弹出。

这样,我们保证队列了的第一个元素永远是当前sliding window里面最大的元素。

class Solution {
    public int[] maxSlidingWindow(int[] nums, int k) {        
        if (nums.length == 0) {
            return new int[0];
        }
        
        int[] res = new int[nums.length - k + 1];                
        Deque<Integer> deque = new LinkedList<Integer>();
        
        for (int i = 0; i < nums.length; i++) {
            if (!deque.isEmpty() && deque.peekFirst() < i - k + 1) {
                deque.pollFirst();
            }
            while (!deque.isEmpty() && nums[deque.peekLast()] < nums[i]) {
                deque.pollLast();
            }
            deque.offer(i);
            if (i >= k - 1) {
                res[i - k + 1] = nums[deque.peekFirst()];
            }
        }
        
        return res;
    }
}

 

Sliding Window Maximum

标签:from   元素   and   number   linear   ati   ber   you   last   

原文地址:https://www.cnblogs.com/NickyYe/p/9961238.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!