https://oj.ismdeep.com/problem?id=2388

#include <bits/stdc++.h>
#define INF 0x3f3f3f3f
#define d(x) cout << (x) << endl
using namespace std;
typedef long long ll;
const int N = 1e6 + 10;
const int M = 2020;
int a[N]; //原始資料
int b[M]; //記錄區間[l, i]中每種數出現次數
int n, m;
int main()
{
int ans = 0, res = 0, MIN = INF; //res代表出現過幾種數
scanf("%d%d", &n, &m);
int l = 1;
for (int i = 1; i <= n; i++)
{
scanf("%d", &a[i]);
if (!a[i]) //跳過零
continue;
if (!b[a[i]]) //某種數第一次出現res++
res++;
b[a[i]]++; //記錄每種數出現次數
while (a[l] == 0)
l++; //跳過零
while (b[a[l]] > 1) //如果在區間 l, i中出現過a[l],去重
{
b[a[l]]--;
l++; //右移l
while (a[l] == 0)
l++;
}
if (res == m)
MIN = min(MIN, i - l + 1);
}
if (res != m)
cout << -1 << endl;
else
cout << MIN << endl;
return 0;
}