从左往右延伸,用一个set存储当前序列,向右延伸的时候如果元素已经在set中存在,则增大左边界;如果不存在,则把新增右边界的元素放到set中。
AC代码:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cstring>
#include <string>
#include <sstream>
#include <vector>
#include <set>
#include <map>
#include <algorithm>
#include <stack>
#include <queue>
#include <bitset>
#include <cassert>
#include <cmath>
using namespace std;
const int maxn = 1000005;
int snowflakes[maxn];
int main()
{
<span style="white-space:pre"> </span>ios::sync_with_stdio(false);
<span style="white-space:pre"> </span>int T;
<span style="white-space:pre"> </span>cin >> T;
<span style="white-space:pre"> </span>while (T--) {
<span style="white-space:pre"> </span>int n;
<span style="white-space:pre"> </span>cin >> n;
<span style="white-space:pre"> </span>for (int i = 0; i < n; i++) {
<span style="white-space:pre"> </span>cin >> snowflakes[i];
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>// 存放当前序列的所有元素
<span style="white-space:pre"> </span>set<int> s;
<span style="white-space:pre"> </span>int letfP = 0, rightP = 0, ans = 0;
<span style="white-space:pre"> </span>while (rightP < n) {
<span style="white-space:pre"> </span>while (rightP < n && !s.count(snowflakes[rightP])) {
<span style="white-space:pre"> </span>s.insert(snowflakes[rightP++]);
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>ans = max(ans, rightP - letfP);
<span style="white-space:pre"> </span>s.erase(snowflakes[letfP++]); // 增大左边界
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>cout << ans << endl;
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>return 0;
}