給定一個長度為n的整數序列,請找出最長的不包含重復數字的連續子序列,輸出它的長度。
輸入格式
第一行包含整數n。
第二行包含n個整數(均在0~100000范圍內),表示整數序列。
輸出格式
共一行,包含一個整數,表示最長的不包含重復數字的連續子序列的長度。
數據范圍
1≤n≤100000
輸入樣例:
5 1 2 2 3 5
輸出樣例:
3
注意這里是連續,算法與LeetCode第八題類似
算法:雙指針,哈希。
#include<iostream> #include<vector> #include<unordered_map> #include<algorithm> using namespace std; int main(void){ int n,res=0,j=0; cin>>n; vector<int>f(n); unordered_map<int,int>h; for(int i=0;i<n;i++)cin>>f[i]; for(int i=0;i<n;i++){ h[f[i]]++; while(j<=i&&h[f[i]]>1)h[f[j++]]--; res=max(res,i-j+1); } cout<<res<<endl; return 0; }