面试题 求最大长度自然序子序列,输出长度和子序列下标

面试题 求最大长度自然序子序列,输出长度和子序列下标(从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;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值