239. 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. Return the max sliding window.
Example:
Input: nums =[1,3,-1,-3,5,3,6,7]
, and k = 3 Output:[3,3,5,5,6,7] Explanation:
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
Note:
You may assume k is always valid, 1 ≤ k ≤ input array's size for non-empty array.
Follow up:
Could you solve it in linear time?
Approach #1: C++. [brute force]
class Solution { public: vector<int> maxSlidingWindow2(vector<int>& nums, int k) { vector<int> ans; if (nums.empty()) return ans; for (int i = 0; i + k <= nums.size(); ++i) { vector<int> temp(nums.begin()+i, nums.begin()+i+k); ans.push_back(*max_element(temp.begin(), temp.end())); } return ans; } };
Approach #1: Java. [deque]
class Solution { public int[] maxSlidingWindow(int[] nums, int k) { if (nums == null || k < 0) return new int[0]; int n = nums.length; int[] r = new int[n-k+1]; int ri = 0; Deque<Integer> q = new ArrayDeque<>(); for (int i = 0; i < n; ++i) { while (!q.isEmpty() && q.peek() < i-k+1) q.poll(); while (!q.isEmpty() && nums[q.peekLast()] < nums[i]) q.pollLast(); q.offer(i); if (i >= k-1) { r[ri++] = nums[q.peek()]; } } return r; } }
Appraoch #3: Python. [deque]
from collections import deque class Solution(object): def maxSlidingWindow(self, nums, k): """ :type nums: List[int] :type k: int :rtype: List[int] """ if not nums: return [] if k == 0: return nums deq = deque() result = [] for i in range(len(nums)): while len(deq) != 0 and deq[0] < i-k+1: deq.popleft() while len(deq) != 0 and nums[i] > nums[deq[-1]]: deq.pop() deq.append(i) if i >= k-1: result.append(nums[deq[0]]) return result
永远渴望,大智若愚(stay hungry, stay foolish)