leetcode239 - Sliding Window Maximum - hard
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.
Follow up:
Could you solve it in linear time?
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
Constraints:
1 <= nums.length <= 10^5-10^4 <= nums[i] <= 10^41 <= k <= nums.length
总共n-k+1个window。
维护一个长度为k的deque代表window:
1. 用index维护
2. push新的数之前用pop_back把比它小的清掉
3. 长度到k了:dq.front() == i-k,用pop_front把之前的踢出去
4. window内单调递减,每个window的max都在front,从i >= k-1开始
Time O(n)
实现:
class Solution { public: vector<int> maxSlidingWindow(vector<int>& nums, int k) { vector<int> res; deque<int> dq; for (int i=0; i<nums.size(); i++){ while (!dq.empty() && nums[i] >= nums[dq.back()]) dq.pop_back(); dq.push_back(i); if (dq.front() == i-k) dq.pop_front(); if (i >= k-1) res.push_back(nums[dq.front()]); } return res; } };

浙公网安备 33010602011771号