欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

最长连续序列-leecode

程序员文章站 2024-02-25 10:07:52
...

动态规划解法:

    public static int longestConsecutive(int[] nums) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        if (nums.length == 1) {
            return nums[0];
        }
        int n = nums.length;
        int min = Integer.MAX_VALUE;
        int minIndex = 0;
        for (int i = 0; i < n; i++) {
            if (nums[i] < min) {
                min = nums[i];
                minIndex = i;
            }
        }
        int[] C = new int[n];
        C[minIndex] = 1;
        Integer[] numsInteger = Arrays.stream(nums).boxed().toArray(Integer[]::new);
        for (int i = n - 1; i >= 0; i--) {
            if (nums[i] == min) {
                continue;
            }
            int preIndex = new ArrayList<>(Arrays.asList(numsInteger)).indexOf(nums[i] - 1);
            if (preIndex != -1) {
                C[i] = C[preIndex] + 1;
            } else {
                C[i] = 1;
            }
        }
        int max = Integer.MIN_VALUE;
        for (int i = 0; i < n; i++) {
            if (C[i] > max) {
                max = C[i];
            }
        }
        return max;
    }

未完待优化。