题目:
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]
.
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?
解:
维护一个双端队列保存可能成为当前窗口最大值的所有候选值的索引,队列中的索引表示的值递减,即队列第一个元素为队列中最大值
对于题目给的例子:
首先进队数组中第一个元素1的索引0,当到达第二个值3时,出队索引0,因为其代表的值1不可能成为窗口中的最大值(因为比3小),
到达第三个值-1,比当前队列中索引代表的值3小,必须进队,因为等下如果3从左侧滑出窗口,-1可能成为窗口的最大值。
dq: (1) 3 -1 -3 5(先出队3(超出窗口),接着出队队尾的-1,-3(小于5))
Java代码:
public class Solution { public int[] maxSlidingWindow(int[] nums, int k) { if(nums == null || nums.length == 0) return nums; int len = nums.length; int[] result = new int[len-k+1]; //结果数组 int ri = 0; //存储递减值的索引的队列 Deque<Integer> dq = new ArrayDeque<Integer>(); for(int i=0; i<len; i++){ //出队超出窗口的索引 if(!dq.isEmpty() && dq.peek() < i-k+1) dq.poll(); //当窗口末尾即队列尾的数比当前滑进的数小,则出队 while(!dq.isEmpty() && nums[dq.peekLast()] < nums[i]) dq.pollLast(); dq.offer(i); //窗口满数时,把最大值加入结果数组 if(i >= k-1) result[ri++] = nums[dq.peek()]; } return result; } }
Python代码:
class Solution: # @param {integer[]} nums # @param {integer} k # @return {integer[]} def maxSlidingWindow(self, nums, k): d = collections.deque() re = [] for i, v in enumerate(nums): while d and nums[d[-1]] < v: d.pop() d.append(i) if d[0] == i-k: d.popleft() if i >= k-1: re.append(nums[d[0]]) return re