肯定是有问题的,应该是记录次数而不是只记录存不存在,这样在左指针右移的时候无法判断删去这个数之后究竟l~r区间内是否还有这个数。
而且好像程序里根本没有`cnt--`这个操作吧?
应该在
```cpp
while(flag[a[l]]>1)
{
flag[a[l]]--;
l++;
}
```
这段代码里处理一下cnt的减法吧
by weak_in_code @ 2024-02-25 19:02:01
@[XingChen_MoNian](/user/920938)
by weak_in_code @ 2024-02-25 19:04:20
帮你改了,加了注释。
```cpp
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<cmath>
#include<queue>
#include<vector>
#include<algorithm>
using namespace std;
typedef long long ll;
const int N=1e6+10;
int a[N],flag[N];
int main(){
// freopen(".in","r",stdin);
// freopen(".out","w",stdout);
ios::sync_with_stdio(false);
cin.tie(0),cout.tie(0);
int n,m;
cin>>n>>m;
for(int i=1;i<=n;i++){
cin>>a[i];
}
int l=1,cnt=0,tot=0x7FFFFFFF,ansl,ansr;
for(int r=1;r<=n;r++){
flag[a[r]]++;//记录次数
if(flag[a[r]]==1) cnt++;//第一次出现这个数
while(flag[a[l]]>1){
flag[a[l]]--;
if(flag[a[l]]==0) cnt--;//这个数不再出现在区间内
l++;
}
if(cnt==m){
if(r-l+1<tot){
tot=r-l+1;
ansl=l;
ansr=r;
}
}
}
cout<<ansl<<" "<<ansr;
// fclose(stdin);
// fclose(stdout);
return 0;
}
```
by weak_in_code @ 2024-02-25 19:07:05