- 首先看数据范围 1e5,不大,两种输入方式都可以
- 题目要求是 最长、不重复、连续的区间长度,那就先根据 样例分析,我们理解为有很多个区间,我们只需找到这些区间中,最长的,连续的、补充的区间即可。可以联想到使用双指针维护一个区间。
- 根据模板,我们使用一个快指针枚举整个序列,每次枚举我们需要把它放到 Hashmap 或者另一个数组中,作去重的处理。
- 并且如果有重复的话,我们需要移动到下一个区间。(根据慢指针做区间的移动,直到没有重复的数为止)
- 没有重复,只需枚举下一个数即可。
code with java
import java.util.*;
import java.math.*;
public class Main {
final static int N = 100010;
public static void main(String[] args) {
int[] a = new int[N];
int[] s = new int[N];
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
for (int i = 0; i < n; i++) a[i] = scan.nextInt();
int res = 0;
for (int i = 0, j = 0; i < n; i++) {
s[a[i]]++;
while (s[a[i]] > 1) {
s[a[j]]--;
j++;
}
res = Math.max(res, i - j + 1);
}
System.out.println(res);
}
}
code with c++
#include <iostream>
using namespace std;
const int N = 100010;
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) {
s[a[j]]--;
j++;
}
res = max(res, i - j + 1);
}
cout << res;
return 0;
}