最長連續不重複子序列
給定一個長度為n的整數序列,請找出最長的不包含重複的數的連續區間,輸出它的長度。
輸入格式
第一行包含整數n。
第二行包含n個整數(均在0~100000範圍内),表示整數序列。
輸出格式
共一行,包含一個整數,表示最長的不包含重複的數的連續區間的長度。
資料範圍:1≤n≤100000
輸入樣例:
5
1 2 2 3 5
輸出樣例:
3
暴力做法:O(n2)
雙指針做法:O(n),結構:for(int r=0,l=0;r<n;r++)
#include<iostream>
#include<cstdio>
using namespace std;
const int MAXN=100010;
int a[MAXN],s[MAXN],n,res;
int main(){
scanf("%d",&n);
for(int i=0;i<n;i++) scanf("%d",a+i);
for(int r=0,l=0;r<n;r++){//for循環結構雙指針算法,s[a[r]]表示a[r]這個數出現了幾次
s[a[r]]++;
while(s[a[r]]>1){
s[a[l]]--;
l++;
}
res=max(res,r-l+1);
}
printf("%d\n",res);
return 0;
}
判斷子序列
給定一個長度為 n 的整數序列 a1,a2,…,an 以及一個長度為 m 的整數序列 b1,b2,…,bm。
請你判斷 a 序列是否為 b 序列的子序列。
子序列指序列的一部分項按原有次序排列而得的序列,例如序列 {a1,a3,a5} 是序列 {a1,a2,a3,a4,a5} 的一個子序列。
輸入格式
第一行包含兩個整數 n,m。
第二行包含 n 個整數,表示 a1,a2,…,an。
第三行包含 m 個整數,表示 b1,b2,…,bm。
輸出格式
如果 a 序列是 b 序列的子序列,輸出一行 Yes。
否則,輸出 No。
資料範圍
1≤n≤m≤105,
−109≤ai,bi≤109
輸入樣例:
3 5
1 3 5
1 2 3 4 5
輸出樣例:
Yes
暴力做法:O(n2)
雙指針做法:O(n)
#include<iostream>
#include<cstdio>
using namespace std;
int a[100010],b[100010];
int main(){
int x,y,cnt=0;
scanf("%d%d",&x,&y);
for(int i=0;i<x;i++) scanf("%d",a+i);
for(int i=0;i<y;i++){//i,stt雙指針
scanf("%d",b+i);
if(b[i]==a[cnt]&&cnt<x) cnt++;
}
if(cnt==x) printf("Yes");
else printf("No");
return 0;
}