尺取法,同向扫描,代码风格学习的罗勇军的博客,然后这道题的关键就是每个知识点出现的次数要大于等于1,如果这个前提忘记或者没有想明白会出错,
#include <bits/stdc++.h>
#define fi first
#define se second
#define pb push_back
#define all(x) (x).begin(), (x).end()
using namespace std;
typedef long long ll;
typedef vector<int> vi;
typedef pair<int, int> pa;
const int maxn = 1e6 + 5;
int a[maxn];
int hashtable[maxn];
int main() {
int n;
cin >> n;
int cnt = 1;
map<int, int> mp;
for (int i = 0; i < n; i++) {
scanf("%d", &a[i]);
if (mp.find(a[i]) == mp.end()) {
mp[a[i]] = cnt++;
a[i] = cnt - 1;
} else a[i] = mp[a[i]];
}
cnt--;
int i = 0, j = 0;
int res = 1;
hashtable[a[i]] = 1;
int ans = maxn;
while (j < n) {
if (res == cnt) {
ans = min(ans, j - i + 1);
hashtable[a[i]]--;
if (!hashtable[a[i]]) res--;
i++;
if (i > j) { res = 1; hashtable[a[i]] = 1; j++; }
} else if (res < cnt) {
j++;
if (!hashtable[a[j]]) {
res++;
hashtable[a[j]] = 1;
} else hashtable[a[j]]++;
}
}
cout << ans;
return 0;
}