思想:
使用双指针法
模板:
for(int i = 0, j = 0; i < n; i ++){
while(j < i && compare(i, j)){
//...
}
}
个人总结:
此时没有学习哈希,可以定义一个数组表示子序列中数字出现的次数,每一次进入for循环,对应数字的数组 s 中的索引位置会加1。然后在while 中进行判断。
代码如下:
package cn.liyi.day06;
import java.util.Scanner;
public class Demo799 {
public static int N = 10010;
public static int[] a = new int[N];
public static int[] s = new int[N];
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入数组的长度:");
int n = sc.nextInt();
System.out.println("请输入数组的元素:");
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
}
int ans = 0;
for(int i = 0, j = 0; i < n; i ++){
s[a[i]] ++;
while(j < i && s[a[i]] > 1){
s[a[i]] --;
j ++;
}
ans = Math.max(ans,i - j + 1);
}
System.out.println("最长在连续不重复子序列的长度是:" + ans);
}
}