题目地址:
https://www.acwing.com/problem/content/801/
给定一个长 n n n的整数数列 A A A,求其最长无重复数的子区间长度。
输入格式:
第一行包含整数
n
n
n。第二行包含
n
n
n个整数(均在
0
∼
100000
0\sim 100000
0∼100000范围内),表示整数序列。
输出格式:
共一行,包含一个整数,表示最长的不包含重复的数的连续区间的长度。
数据范围:
1
≤
n
≤
100000
1\le n\le 100000
1≤n≤100000
思路是双指针。我们枚举子区间右端点 i i i,并维护满足条件的区间的最左的左端点 j j j,容易发现,当 i i i右移一格的时候,左端点不会回退,并且 A [ i ] A[i] A[i]是唯一可能出现重复的数字。当出现重复了,就右移 j j j缩小区间,直到没有重复为止。代码如下:
#include <iostream>
#include <unordered_set>
using namespace std;
const int N = 100010;
int n, a[N];
int main() {
cin >> n;
for (int i = 0; i < n; i++) scanf("%d", &a[i]);
int res = 0;
unordered_set<int> st;
for (int i = 0, j = 0; i < n; i++) {
while (st.count(a[i])) st.erase(a[j++]);
st.insert(a[i]);
res = max(res, i - j + 1);
}
cout << res << endl;
}
时空复杂度 O ( n ) O(n) O(n)。