思路
其实是一道典型的双指针问题,只要一直往后去输入数据,如果遇到重复的数据,就让begin指针往后移,直到重复的元素不再子序列内,在读入新数据就可以了,每次遇到重复数据就把maxlength和当前的length比较去大值,就可以了
代码
#include <stdio.h>
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;
const int N = 1e5 + 7;
int a[N], s[N];
int main() {
int n, res = 0;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> a[i];
}
for (int i = 0, j = 0; i < n; i++) {
s[a[i]]++; //重复的数字是由当前的值引起的
while (s[a[i]] > 1) { //j一直往i移动,直到当前值只出现一次为止
s[a[j]]--;
j++;
}
res = max(res, i - j + 1);//取大值
}
cout << res << endl;
return 0;
}