一个比较经典的题目,这里用了一个hash表存储,之前在leetcode上也刷过类似的题目,此处是i为右指针,j为左指针,一旦发现当前有重复就让左指针右移,直到不重复为止。
    时间复杂度:Acwing 799.最长连续不重复子序列 - 图1
    空间复杂度:Acwing 799.最长连续不重复子序列 - 图2

    1. #include<iostream>
    2. #include<unordered_map>
    3. using namespace std;
    4. int n;
    5. const int N = 1e5+10;
    6. int a[N];
    7. unordered_map<int,int> umap;
    8. int main(){
    9. scanf("%d",&n);
    10. for(int i=0;i<n;i++) scanf("%d",&a[i]);
    11. int res = 0;
    12. for(int i=0,j=0;i<n;i++){
    13. umap[a[i]]++;
    14. while(umap[a[i]]>1){
    15. umap[a[j]]--;
    16. j++;
    17. }
    18. res = max(res,i-j+1);
    19. }
    20. cout << res << endl;
    21. return 0;
    22. }