思路:
- 将数组升序排序,枚举数组中的每个数 x,考虑以其为起点,不断尝试匹配 x+1, x+2,⋯ 是否存在,假设最长匹配到了 x+y,那么以 x 为起点的最长连续序列即为 x, x+1, x+2,⋯,x+y,其长度为 y+1 for循环套while循环实现
- 要枚举的数 x 一定是在数组中不存在前驱数 x-1 的,否则x-1为起点的子序列长度必大于以x为起点的子序列,此功能可用HashSet实现
- 由于需要输出子序列下标,则在排序之前,用HashMap存储下每个数值及下标
- 由于子序列长度不定,则先用list存放,最后转成数组
import java.util.*;
public class LongestConsecutive {
static List list = new linkedList<>();//存放最后结果
public static void main(String[] args) {
int result = longestConsecutive(new int[]{3, 2, 4, 4, 5, 7,6});//result返回子序列长度
System.out.println(result);
int[] temp = new int[list.size()];
for(int i = 0;i map = new HashMap<>();//存储值及对应下标
HashSet set = new HashSet<>();
int n = arr.length;
int i ;
for(i = 0;i max){//此子序列长度大于存在的子序列
list.clear();
max = y-x;
for(int j = x;j 


