当前位置:网站首页>滑动窗口最值问题

滑动窗口最值问题

2022-06-10 17:44:00 星光技术人

滑动窗口最值问题

基础思想

在求数组窗口最值的时候,需要维护一个双向的队列;对于最大值问题需要保证维护过程中队列绝对递减;

  • 步骤:两个 指针L和R;
    1) 指针R右移的时候,将经过的索引加入队列,并根据队列里边已经存在的索引来决定操作,在往队列尾部加入元素的时候,一定要保证待加入的索引值对应的元素绝对小于队列尾部索引值对应的元素;如果不满足条件,那么就把队列尾部 的索引值弹出,直到满足条件的时候加入;
    2) 指针L右移的时候,L指针经过的元素对应的索引值在队列中已经失效,判断该失效元素是否为目前队列的队首元素,如果是的话,就从队首弹出;

点拨:维护队首元素为目前窗口的最大元素对应的索引;

例题

在这里插入图片描述

#include<iostream>
#include<deque>
#include<vector>
using namespace std;

int main()
{
    
	vector<int> res;
	deque<int> que_idx;
	int S = 3;//窗口大小
	vector<int> in_vec = {
     4,3,5,4,3,3,6,7 };
	
	for (int i = 0; i < S; i++)
	{
    
		while(!que_idx.empty() && in_vec[que_idx.back()] <= in_vec[i])
			que_idx.pop_back();
		que_idx.push_back(i);		
	}

	res.push_back(in_vec[que_idx.front()]);

	for (int j = 1, k = S; j < in_vec.size() && k < in_vec.size(); j++, k++)
	{
    
		if (j-1 == que_idx.front())
		{
    
			que_idx.pop_front();
		}
		while (!que_idx.empty() && in_vec[que_idx.back()] <= in_vec[k])
			que_idx.pop_back();
		que_idx.push_back(k);
		res.push_back(in_vec[que_idx.front()]);
	}
	for (int m = 0; m < res.size(); m++)
	{
    
		cout << res[m] << " ";
	}
	return 0;
}

原网站

版权声明
本文为[星光技术人]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qhu1600417010/article/details/124950909