lintcode(362)滑动窗口的最大值

来源:互联网 发布:手机卡iphone7在线软件 编辑:程序博客网 时间:2024/06/06 01:03

Description:

给出一个可能包含重复的整数数组,和一个大小为 k 的滑动窗口, 从左到右在数组中滑动这个窗口,找到数组中每个窗口内的最大值。

Explanation:

给出数组 [1,2,7,7,8], 滑动窗口大小为 k = 3. 返回 [7,7,8].

解释:

最开始,窗口的状态如下:

[|1, 2 ,7| ,7 , 8], 最大值为 7;

然后窗口向右移动一位:

[1, |2, 7, 7|, 8], 最大值为 7;

最后窗口再向右移动一位:

[1, 2, |7, 7, 8|], 最大值为 8.

Challenge:

O(n)时间,O(k)的额外空间

Solution:

一开始考虑使用栈来实现,每次推入新值,从stack的peek开始推出比当前值小的数,但是发现【5,8,6,7 ,4,3】,k = 3时,推入4,8被推出,但是6,7都比4大没被推出,但是6<7应该被推出,所以需要遍历一遍缓存的数,保证peek是当前最大值,这样时间复杂度O(nklogk),不符合要求了。

然后使用双端队列,每次推入新值时,保证deque内长度小于等于k,在peekLast推出比当前小的值,以此保证peekFirst一直是最大值。

双端队列的文档:

https://docs.oracle.com/javase/8/docs/api/java/util/Deque.html

我觉得难点应该就是双端队列的使用吧,时间复杂度可能写的不对-_-||

public class Solution {    /**     * @param nums: A list of integers.     * @return: The maximum number inside the window at each moving.     */    public ArrayList<Integer> maxSlidingWindow(int[] nums, int k) {        // write your code here        Deque<Integer> deque = new LinkedList<Integer>();        ArrayList<Integer> result = new ArrayList<Integer>();        for(int i = 0 ; i< nums.length ; i++){            while(!deque.isEmpty() && i - deque.peekFirst() >= k){                deque.pollFirst();            }            while(!deque.isEmpty() && nums[deque.peekLast()] <= nums[i]){                deque.pollLast();            }            deque.offerLast(i);            if(i >= k - 1){                result.add(nums[deque.peekFirst()]);            }        }                return result;    }}