双指针——最长连续不重复子序列(例)

给定一个长度为n的整数序列,找出最长的不包含重复的数的连续区间,输出它的长度。

数据范围:1\leq n\leq 10^{5_{}}

 

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

 

#include <iostream>  //C++标准库中的头文件.用于控制台输入和输出。
#include <cstring>   //用于处理字符串的函数和操作
#include <algorithm> //提供了许多常用的算法函数,用于对数据进行排序、查找、变换和操作等操作。
using namespace std; // 这一句也不能少
const int N = 100010;

int n;
int q[N];
int cnt[N];
int main()
{
    scanf("%d", &n);
    for (int i = 1; i <= n; i++)
    {
        scanf("%d", &q[i]);
    }
    int res = 1;
    for (int i = 1, j = 1; i <= n; i++)
    {
        cnt[q[i]]++;
        while (cnt[q[i]] > 1)
        {
            cnt[q[j]]--;
            j++;
        }
        res = max(res, i - j + 1);
    }
    printf("%d", res);
    return 0;
}

 

posted on 2023-05-13 18:23  gjktOvO  阅读(24)  评论(0)    收藏  举报

导航