双指针来源:暴力解法的优化
定义两个指针分别指向最长连续不重复子序列的起始位置和终止位置。
起始位置指向第一个元素,终止位置从1开始依次遍历,若当前终止位置的数值出现重复,就把起始位置的指针移动到与当前终止位置数值相同的元素(在终止位置之前)的下一个位置,再继续进行终止位置的遍历。
期间不断计算起始位置到终止位置的距离,并更新最大长度,即可求出最长连续不重复子序列的长度。
#include<iostream>
#include<algorithm>
using namespace std;
int a[100100];
int s[100100];
int main(){
int n;
cin>>n;
for(int i=1;i<=n;i++){
cin>>a[i];
}
int res=0;
for(int i=1,j=1;i<=n;i++){
s[a[i]]++;
while(s[a[i]]>1){
s[a[j]]--;
j++;
}
res=max(res,i-j+1);
}
cout<<res;
return 0;
}