题目链接: CodeForces - 616D
这是一个尺取法的问题,涉及到双指针,第一次写到第六个点就wa了,查了一下资料发现有几个容易忽略的点
双指针思路没有什么问题,需要注意每个数字可能出现不止一次,所以标记的数据不能是bool而应该是int,每出现一个新出现的数字,计数器cnt++,否则对应的尺取区间里面对应的st[a[j]]++. 当cnt > k应该移动 j,每移动一次,对应的st[a[j]]–,j++, 只有当st[a[j]] == 0的时候cnt–,才满足题目要求,然后每次更新一下答案,时间复杂度O(n)
#include <iostream>
#include <algorithm>
#include <cstdlib>
#include <iomanip>
#include <cstring>
#include <cmath>
#include <vector>
#include <queue>
#include <deque>
#include <set>
#include <map>
#include <stack>
using namespace std;
typedef pair<int,int> PII;
typedef long long ll;
const int inf = 0x3f3f3f3f;
const long long INF = 0x3f3f3f3f3f3f3f3f;
const double eps = 1e-6;
const double PI = acos(-1);
const int N =1e6 + 10;
int n, k;
int a[N];
int ansl = 1, ansr = 1, cnt;
int st[N];
int main()
{
scanf("%d%d", &n, &k);
for(int i = 1;i <= n;i++) scanf("%d", &a[i]);
int j = 1;
for(int i = 1;i <= n;i++)
{
st[a[i]]++;
if(st[a[i]] == 1) cnt++;
while(cnt > k)
{
st[a[j]]--;
if(!st[a[j]]) cnt--;
j++;
}
if(i - j > ansr - ansl) ansl = j, ansr = i;
}
printf("%d %d\n",ansl, ansr);
return 0;
}