双指针算法-最长不重复子序列

思路

这里的 i 才是主要的遍历指针, j 是用来剔除元素以满足题目要求的。

image-20231224065535487

代码

#include<iostream>
using namespace std;

const int N = 1e5 + 10;

int n, res;
int a[N], s[N];


int main() {
    cin >> n;
    for (int i = 0; i < n; i++) cin >> a[i];
    
    for (int i = 0, j = 0; i < n; i++) {
        s[a[i]]++;
        while (s[a[i]] > 1) {
            s[a[j]] --;
            j++;
        }
        
        res = max(res, i - j + 1);
    }
    
    cout << res << endl;
    return 0;
}
posted @ 2023-12-24 06:58  vLiion  阅读(20)  评论(0)    收藏  举报