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

Note: 
You may assume k is always valid, ie: 1 ≤ k ≤ input array's size for non-empty array.

Follow up:
Could you solve it in linear time?

分析:

借助双端队列

队列中保存滑动窗口中当前后i个元素的最大值的下标;

本来是想申请一个数组保存当前后i个元素中的最大值,但是这样的话,每次滑动窗口都要更新数组,增加了时间复杂度;借助动态数组,保存最大值下标,这样只要(从左往右)当前元素下标小于队列头的元素,则队列头元素所指的数组元素就是当前后i个元素的最大值;如果相等,则删除队头元素,然后循环;

正着求后i个元素的最大值!!!

参考代码:

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


你可能感兴趣的:(Leetcode)