Sliding Window Maximum
Given an array of n integer with duplicate number, and a moving window(size k), move the window at each iteration from the start of the array, find the maximum number inside the window at each moving.
这道题可以用Deque做,处于队首的元素是当前滑动窗口的最大值,直到该值被替换或者直到无效(窗口不在包含该值,先处理前k个元素,然后开始计算最大值
窗口右移时的新元素i可以影响到前i-k-1至i+k-1个元素,而队列里面的元素依旧可以影响至当前元素,因此从队尾开始比较删除比当前元素小得队尾元素,直到遇到比该元素大的元素。
然后查看当前队首元素是否有效(其值等于num[i-k]为无效),则将其删除,当前队首元素即为最大值,遍历直至i==n-1;
//
// main.cpp
// Sliding Window Maximum
//
// Created by 孟文斌 on 15/4/30.
// Copyright (c) 2015年 孟文斌. All rights reserved.
//
#include <iostream>
#include <vector>
#include <deque>
using namespace std;
class Solution {
public:
/**
* @param nums: A list of integers.
* @return: The maximum number inside the window at each moving.
*/
vector<int> maxSlidingWindow(vector<int> &nums, int k) {
// write your code here
int n = (int)nums.size();
vector<int> res;
if(!n || !k || k>n) return res;
if(k==1) return nums;
deque<int> q;
int last = nums[0];
q.push_back(last);
for(int i=1;i<k;i++){
while(nums[i] > last){
q.pop_back();
if(q.empty()) break;
last = q.back();
}
last = nums[i];
q.push_back(last);
}
res.push_back(q.front());
for(int i=k;i<n;i++){
while(nums[i] > last){
q.pop_back();
if(q.empty()) break;
last = q.back();
}
last = nums[i];
q.push_back(last);
if(nums[i-k] == q.front()){
q.pop_front();
}
res.push_back(q.front());
}
return res;
}
};
void displayVector(vector<int> res){
for(int i=0;i<res.size();i++){
cout<<res[i]<<" ";
}
cout<<endl;
}
int main(int argc, const char * argv[]) {
Solution sol;
vector<int> nums = {142,38,100,53,22,84,168,50,194,136,111,13,47,45,151,164,126,47,106,124,183,8,87,38,91,121,102,46,82,195,53,18,11,165,61};
displayVector(sol.maxSlidingWindow(nums, 35));
return 0;
}