题意:输入一个长度为n(n)的序列A,找到一个尽量长的连续子序列,使得序列中没有相同元素。
分析:两种方法,一是以序列为对象搜索,每次向前增加一个,有重复就减少。
二是,找到相同的元素位置,找出相同元素之间距离最大的。
#include<iostream>
#include<string>
#include<sstream>
#include<set>
#include<algorithm>
#include<vector>
using namespace std;
const int maxn = 1000000 + 100;
int A[maxn];
int main() {
int kase;
int n;
cin >> kase;
while (kase--) {
cin >> n;
for (int i = 0; i < n; i++) {
cin >> A[i];
}
set<int>s;
int L = 0, R = 0, ans = 0;
while (R < n) {
while (R<n&&!s.count(A[R]))s.insert(A[R++]);
ans = max(ans, R - L);
s.erase(A[L++]);
}
cout << ans << endl;
}
return 0;
}
#include<iostream>
#include<string>
#include<sstream>
#include<set>
#include<algorithm>
#include<vector>
#include<map>
using namespace std;
const int maxn = 1000000 + 100;
int A[maxn];
int last[maxn];
int main() {
int kase;
int n;
map<int, int>mp;
cin >> kase;
while (kase--) {
mp.clear();
cin >> n;
for (int i = 0; i < n; i++) {
cin >> A[i];
if (!mp.count(A[i]))last[i] = -1;
else last[i] = mp[A[i]];
mp[A[i]] = i;//更新位置
}
int L = 0, R = 0, ans = 0;
while (R < n) {//找出长度最大的
while (R < n&&last[R] < L)R++;
ans = max(ans, R - L);
L++;
}
cout << ans << endl;
}
return 0;
}