简要:
我目前总结了两种模型,一种是一般模型,一种是特定模型。我们通过几道
题目来总结这两套模板。
相关题目链接:
Acwing第79题(滑动窗口的最大值)https://www.acwing.com/problem/content/description/75/
相关题目:
解题思路:
由于涉及到求最大值,我们要用到双端队列模型,不能使用一般模型,题目的具体思路我不会讲。
相关代码:
class Solution {
public:
int b[100001];
vector<int> maxInWindows(vector<int>& nums, int k) {
vector<int> b;
deque<int> a;
//处理队头
for(int i=0;i<nums.size();i++){
while(a.size()!=0&&i-k>=a.front()){
a.pop_front();
}
//处理队尾
while(a.size()!=0&&nums[i]>nums[a.back()]){
a.pop_back();
}
a.push_back(i);
if(i>=k-1){
b.push_back(nums[a.front()]);
}
}
return b;
}
};
相关题目链接:
Acwing第4394题(最长连续子序列)https://www.acwing.com/problem/content/description/4397/
相关题目:
解题思路:
用一般模型来解题,题目的具体思路我不会讲。
相关代码:
#include<iostream>
using namespace std;
int n,k;
int a[1000001];
int h[1000001];
int ant;
int res;
int l,r;
int main(){
cin>>n>>k;
for(int i=0;i<n;i++) cin>>a[i];
for(int i=0,j=0;i<n;i++){
if(h[a[i]]==0){
ant++;
}
h[a[i]]++;
while(ant>k){
if(h[a[j]]==1){
ant--;
}
h[a[j]]--;
j++;
}
if(res<i-j+1){
res=i-j+1;
l=j+1;
r=i+1;
}
}
cout<<l<<" "<<r;
return 0;
}