Leetcode 239. Sliding Window Maximum

    xiaoxiao2021-04-13  28

    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?

    用一个滑窗在数组上滑动,求滑动到每个位置时,滑窗内数字的最大值,线性时间内完成。

    使用双端队列完成,队列记录数组中的下标,维护多个单调递减区间。

    当当前下标和队列首的元素相差超过k-1时,说明滑窗超过了既定大小,需要把前一个元素扔掉。

    因为要维护单调递增,所以每次加入一个新的下标时,需要将新加入的数和队列尾的数字比较,扔掉比新加入的数小的数,因为它们不可能是滑窗内的最大值。

    当下标大于等于k-1的时候,说明要开始记录滑窗的最大值了。

    class Solution { public: vector<int> maxSlidingWindow(vector<int>& nums, int k) { vector<int> res; deque<int> q; for(int i = 0; i < nums.size(); i++) { if(!q.empty() && i - q.front() >= k) q.pop_front(); while(!q.empty() && nums[q.back()] <= nums[i]) q.pop_back(); q.push_back(i); if(i >= k - 1) res.push_back(nums[q.front()]); } return res; } };

    转载请注明原文地址: https://ju.6miu.com/read-669432.html

    最新回复(0)