面试题 求最大长度自然序子序列,输出长度和子序列下标(从1开始)
思路:
- 将数组升序排序,枚举数组中的每个数 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<Integer> 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<list.size();i++){
temp[i] = list.get(i);
}
System.out.println(Arrays.toString(temp));
}
public static int longestConsecutive(int[] arr){
HashMap<Integer,Integer> map = new HashMap<>();//存储值及对应下标
HashSet<Integer> set = new HashSet<>();
int n = arr.length;
int i ;
for(i = 0;i<n;i++){
set.add(arr[i]);//将数值存放在set中
if(map.containsKey(arr[i])) continue;//防止同一个数值出现多次,只记录第一次出现的下标
map.put(arr[i],i);
}
Arrays.sort(arr);//升序排
int max = 0;
for(i = 0;i<n;i++){//枚举数组的值
int x = arr[i];
int y = x;
if(set.contains(x-1)) continue;//存在先驱数值,则跳过
while(set.contains(y)) y = y + 1;//while循环找到此子序列的最后节点
if(y-x > max){//此子序列长度大于存在的子序列
list.clear();
max = y-x;
for(int j = x;j<y;j++){
list.add(map.get(j)+1);//将子序列元素对应的初始索引加入list
}
}
}
return max;
}
}