题目:
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?
Hint:
用Heap可以实现O((n-k)lgk)复杂度。要求Linear Time的话只能借助Deque。Deque的队首始终保持最大元素。然后根据一定条件进Queue即可。
C++版:
class Solution { public: vector<int> maxSlidingWindow(vector<int>& nums, int k) { vector<int> result; if(nums.size() == 0 || k == 0) return result; deque<int> buffer; for(int i = 0; i < k; i++) { bufferModifier(buffer, nums[i]); } result.push_back(buffer.front()); for(int i = k; i < nums.size(); i++) { if(buffer.front() == nums[i-k]) buffer.pop_front(); bufferModifier(buffer, nums[i]); result.push_back(buffer.front()); } return result; } void bufferModifier(deque<int>& buffer, int n) { if(buffer.size() == 0) buffer.push_back(n); else if(buffer.front() < n) { buffer.clear(); buffer.push_back(n); } else { while(buffer.back() < n) buffer.pop_back(); buffer.push_back(n); } } };
public class Solution { public int[] maxSlidingWindow(int[] nums, int k) { if(nums.length == 0) return new int[0]; Deque<Integer> buffer = new LinkedList<>(); for(int i = 0; i < k; i++) { bufferModifier(buffer, nums[i]); } int[] result = new int[nums.length - k + 1]; result[0] = buffer.getFirst(); for(int i = k; i < nums.length; i++) { if(buffer.getFirst() == nums[i-k]) buffer.pollFirst(); bufferModifier(buffer, nums[i]); result[i-k+1] = buffer.getFirst(); } return result; } public void bufferModifier(Deque<Integer> buffer, int n) { if(buffer.isEmpty()) { buffer.addFirst(n); } else if(n > buffer.getFirst()) { buffer.clear(); buffer.addFirst(n); } else { while(buffer.getLast() < n) buffer.pollLast(); buffer.addLast(n); } } }
class Solution: # @param {integer[]} nums # @param {integer} k # @return {integer[]} def maxSlidingWindow(self, nums, k): if len(nums) == 0: return [] result = [] buffer = [] for i in range(k): self.bufferModifier(buffer, nums[i]) result.append(buffer[0]) for i in range(k, len(nums)): if buffer[0] == nums[i-k]: buffer = buffer[1:] self.bufferModifier(buffer, nums[i]) result.append(buffer[0]) return result def bufferModifier(self, buffer, n): if len(buffer) == 0: buffer.append(n) elif buffer[0] < n: del buffer[:] buffer.append(n) else: while buffer[len(buffer)-1] < n: buffer.pop() buffer.append(n)