最长连续子序列
题目 最长连续子序列
思路分析
与双指针的模版题1基本一样
区间出现的数一定只有两种
所以在维护出现次数的时候 再维护一下数组中有多少种数存在
代码实现
#include<bits/stdc++.h>
using namespace std;
#define endl '\n'
const int N=1e5+10;
int a[N],s[N],cnt;
int n;
int main()
{
ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
cin>>n;
for(int i=0;i<n;i++) cin>>a[i];
int res=0;
for(int i=0,j=0;i<n;i++){
if(!s[a[i]])
cnt++;
s[a[i]]++;
while(cnt>2){
s[a[j]]--;
if(!s[a[j]])
cnt--;
j++;
}
res=max(res,i-j+1);
}
cout<<res<<endl;
return 0;
}
💬 评论