题意:给出一个序列, 要找出最长的连续子序列,不存在重复元素。
紫书题解:假设元素从0开始编号,连续子序列的左端点L,右端点R。起初L=R=0,不断增加R,判断a[R+1]是否在[L,R]这个区间出现过,若出现过,则从set集合中删除a[L](即L向右移动一位)。不断的这样判断直到最后结束即可。
AC代码:
#include<cstdio>
#include<set>
#include<algorithm>
#include<cstring>
using namespace std;
const int maxn = 1e6+5;
int a[maxn];
set<int>st;
int main(){
int T;
scanf("%d",&T);
while(T--){
int n;
scanf("%d",&n);
for(int i = 0; i < n; i++)
scanf("%d",&a[i]);
int cnt = 0;
int L = 0,R = 0;
while(L < n && R < n){
if(st.find(a[R]) != st.end()){
st.erase(a[L]);
L++;
}
else {
st.insert(a[R]);
R++;
}
cnt = max(cnt,R-L);
}
printf("%d\n",cnt);
st.clear();
}
return 0;
}