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; } }

 

你可能感兴趣的:(window)