LeetCode[239] Sliding Window Maximum

来源:互联网 发布:免费字体下载软件 编辑:程序博客网 时间:2024/05/17 04:56

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.

用一个双端队列记录可能成为窗口最大值的索引,队列的头部为确定的窗口最大值索引。每个索引只能保留至多k次,于是当 i - k = index.front() 时就要执行 index.pop_front(),当遇到一个大数的索引时,先前队列中小于该元素的数都不可能成为窗口最大值了,于是要挨个从队尾弹出。窗口最大值一共有 nums.size() - k +1个,于是要从 i >= k - 1 时开始记录。

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

0 0