(五)、双指针 -- 最长连续不重复子序列

一、题干

https://www.acwing.com/problem/content/801/

 

 

 

二、代码

第一种方法,双指针 + 暴力搜索,tle了

#include <iostream>
using namespace std;
const int N = 1e5+5;
int arr[N];
int n;

int  check(int l,int r){
    int val = arr[r];
    for(int i = r-1;i>=l;i--){
        
        if(val == arr[i]){
            return i;
        }
    }
    return 0;
}


int main(){
    scanf("%d",&n);
    for(int i = 0;i<n;i++) scanf("%d",&arr[i]);
    
    int maxx = 0;
    int i ,j;
    for( i = 0, j = 1;i<n;i++){
        int ret = check(j,i);
        if(ret != 0){
            maxx = max(i-j,maxx);
            j = ret + 1;
//            cout<<j<<endl;
        }
    }    
    maxx = max(i-j,maxx);
    cout<<maxx<<endl;
    return 0;
}

AC方法: 双指针 + 数组优化

//  AC代码
#include <iostream>
using namespace std;
const int N = 1e5+5;
int arr[N];
int n,maxx;
int hashh[N];
int main(){
    scanf("%d",&n);
    for(int i = 0;i<n;i++) scanf("%d",&arr[i]);
    
    for(int j = 0, i = 0;i<n;i++){
        hashh[arr[i]]++;
        while(j < i && hashh[arr[i]] > 1){   //双指针维护 [l,r]区间, 当双指针维护的区间出现重复字母时,说明arr[r]是导致重复的字符 
            hashh[arr[j]] --;                 // 我们只需要把 左区间l逐渐向右移动,每次移动hashh[arr[l]]都减一,hashh[arr[r]]不大于1为止,这时说明,重复的字母已经被减去了。 
            j ++;                            //通过这种hash表的方式,省了不少功夫 
        }
        maxx = max(maxx,i-j+1);
    }
    printf("%d\n",maxx);
    return 0;
} 

 

posted @ 2023-01-09 23:22  TLSN  阅读(17)  评论(0)    收藏  举报