最长连续不重复子序列(双指针算法)

题目描述:

给定一个长度为n的整数序列,请找出最长的不包含重复数字的连续区间,输出它的长度。
输入格式
第一行包含整数n。
第二行包含n个整数(均在0~100000范围内),表示整数序列。

输出格式
共一行,包含一个整数,表示最长的不包含重复数字的连续子序列的长度。

数据范围
1≤n≤100000

输入样例:
5
1 2 2 3 5
输出样例:
3

#include
using namespace std;
typedef long long LL;
namespace IO{
     
    inline LL read(){
     
        LL o=0,f=1;char c=getchar();
        while(c<'0'||c>'9'){
     if(c=='-')f=-1;c=getchar();}
        while(c>='0'&&c<='9'){
     o=o*10+c-'0';c=getchar();}
        return o*f;
    }
}using namespace IO;
const int N=1e5+7,base=1e9;
int cnt[N];//记录每个数出现的次数
int pos[N];
int main(){
     
    int n;
    n=read();
    for(int i=0;i<n;i++)pos[i]=read();
    int ans=0;
    for(int i=0,j=0;i<n;i++){
     
        cnt[pos[i]]++;//i位置的数出现的次数+1
        while(j<i&&cnt[pos[i]]>1)cnt[pos[j++]]--;//如果当前位置的数出现重复,就从前面一直往后减每个位置的数的次数,直到当前位置的数不重复则区间内没有重复数
        ans=max(ans,i-j+1);//每次都更新答案
    }
    cout<<ans<<endl;
    return 0;
}

你可能感兴趣的:(题解,算法)