滑动窗口挺有意思的,如果符合条件右端点一直向前走,不符合的话,左端点向前走。
1 #include <bits/stdc++.h> 2 using namespace std; 3 4 set<int> Set; 5 6 const int maxn = 1000000 + 10; 7 int a[maxn]; 8 9 int Scan() { //输入外挂 10 int res = 0; 11 char ch; 12 while((ch = getchar()) >= '0' && ch <= '9') 13 res = res * 10 + (ch - '0'); 14 return res; 15 } 16 17 int main() 18 { 19 //freopen("in.txt", "r", stdin); 20 int T, n; 21 scanf("%d", &T); 22 while(T--) 23 { 24 Set.clear(); 25 scanf("%d", &n); getchar(); 26 for(int i = 0; i < n; ++i) a[i] = Scan(); 27 int L = 0, R = 0, ans = 0; 28 for(; L < n; ++L) 29 { 30 while(R < n &&!Set.count(a[R])) { Set.insert(a[R]); R++; } 31 ans = max(ans, R - L); 32 if(R == n) break; 33 Set.erase(a[L]); 34 } 35 printf("%d ", ans); 36 } 37 38 return 0; 39 }