题目描述:
试求一个整数序列中, 最长的仅包含两个不同整数的连续子序列。如有多个子序列并列最长,输出第一个即可。
输入格式:
第一行包含整数 n。
第二行包含 n 个整数(均在 1~10^5 范围内),表示整数序列。
输出格式:
共两行
第一行包含一个整数,表示最长的仅包含两个不同整数的连续子序列长度m。
第二行包含m个整数,即这个最长的仅包含两个不同整数的连续子序列。
数据范围:
1≤n≤10^5
样例输入:
14 1 1 2 3 2 3 2 3 3 1 1 1 3 1
样例输出:
7 2 3 2 3 2 3 3
时间限制: 1000ms
空间限制: 256MB
使用双指针优化算法
代码实现:
#include<bits/stdc++.h>
using namespace std;
int main(){
long long a[100005],n,x,y,cntx,cnty,L=1,R,ans,start,end;
cin>>n;
for(int i=1;i<=n;i++){
cin>>a[i];
}
//初始化
x=a[1];
R=n;
for(int i=2;i<=n;i++){
if(a[i]!=x){
y=a[i];
R=i;
break;
}
}
cntx=R-1;
cnty=1;
ans=R;
start=1;
end=R;
//主程序
while(R<n){
if(a[++R]==x)cntx++;
else if(a[R]==y)cnty++;
else{
while(cntx&&cnty){
if(a[L]==x)cntx--;
else cnty--;
L++;
}
if(cntx==0)x=a[R],cntx=1;
if(cnty==0)y=a[R],cnty=1;
}
if(R-L+1>ans)ans=R-L+1,start=L,end=R;
}
cout<<ans<<endl;
for(int i=start;i<=end;i++){
cout<<a[i]<<" ";
}
return 0;
}