题目描述
更易理解的双指针
样例
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n, m;
vector<int> balls;
cin >> n >> m;
for (int i = 0; i < n; i ++) {
int k;
cin >> k;
balls.push_back(k);
}
int s[2001] = {0};
int l = 0, r = -1;
int cnt = 0;
int minLen = n + 1;
while (l < n) {
if (r + 1 < n && cnt < m) {
s[balls[r + 1]] ++;
if (s[balls[r + 1]] <= 1 && balls[r + 1] != 0) {
cnt ++;
}
r ++;
} else {
if (cnt == m && r - l + 1 < minLen) {
minLen = r - l + 1;
}
s[balls[l]] --;
if (s[balls[l]] < 1 && balls[l] != 0) {
cnt --;
}
l ++;
}
}
if (minLen == n + 1) {
cout << "-1" << endl;
} else {
cout << minLen << endl;
}
return 0;
}