给出一个序列,要求找出一个最长的连续子序列,使得这个子序列中没有重复的元素。
连续、子序列、不重复,这些关键词都指向滑动窗口
用STL的set和map都会比较慢,我觉得自己写hash会快一些。以后有机会再回来写hash版的吧
Run Time: 1.032s
#define UVa "LT8-7.11572.cpp"
#include<cstdio>
#include<vector>
#include<cstring>
#include<algorithm>
#include<map>
using namespace std;
int main() {
int T, n;
scanf("%d", &T);
for(int kase = 1; kase <= T; kase ++) {
vector<long long> snowflakes;
scanf("%d", &n);
long long tmp;
for(int i = 0; i < n; i ++) {
scanf("%lld", &tmp);
snowflakes.push_back(tmp);
}
map<long long, int> uniq;
int l = 0, r = 0;
int maxsize = 1;
while(r < n) {
int u = snowflakes[r];
if(uniq.count(u) && uniq[u] >= l && uniq[u] < r) { //repeated in current range.
l = uniq[u] + 1;
}
uniq[u] = r;
maxsize = max(maxsize, r - l + 1);
r++;
}
printf("%d\n", maxsize);
}
return 0;
}