【LeetCode热题100】--128. 最长连续序列

128.最长连续序列

【LeetCode热题100】--128. 最长连续序列_第1张图片

先对数组进行排序,不断尝试x+1,x+2,…是否存在,不断枚举并更新答案

class Solution {
    public int longestConsecutive(int[] nums) {
        if (nums == null || nums.length == 0){
            return 0;
        }
        Arrays.sort(nums);
        int maxLength = 1,current = 1;
        for(int i = 1;i<nums.length;i++){
            if(nums[i] - nums[i-1] == 1){
                current++;
                maxLength = Math.max(maxLength,current);
            }else if(nums[i] == nums[i-1]){
                continue;
            }else{
                current = 1;
            }
        }
        return maxLength;
    }
}

对于匹配的过程,暴力的方法是 O ( n ) O(n) O(n)遍历数组去看是否存在这个数,但其实更高效的方法是用一个哈希表存储数组中的数,这样查看一个数是否存在即能优化至 O ( 1 ) O(1) O(1)的时间复杂度。

仅仅是这样我们的算法时间复杂度最坏情况下还是会达到 O ( n 2 ) O(n^2) O(n2)(即外层需要枚举 O ( n ) O(n) O(n)个数,内层需要暴力匹配 $O(n) $次),无法满足题目的要求。但仔细分析这个过程,我们会发现其中执行了很多不必要的枚举,如果已知有一个 x , x + 1 , x + 2 , ⋯   , x + y x,x+1,x+2,⋯ ,x+y x,x+1,x+2,,x+y的连续序列,而我们却重新从 x + 1 x+1 x+1 x + 2 x+2 x+2 或者是 x + y x+y x+y处开始尝试匹配,那么得到的结果肯定不会优于枚举 xxx 为起点的答案,因此我们在外层循环的时候碰到这种情况跳过即可。

那么怎么判断是否跳过呢?由于我们要枚举的数$ x$一定是在数组中不存在前驱数 x − 1 x−1 x1的,不然按照上面的分析我们会从 x − 1 x−1 x1开始尝试匹配,因此我们每次在哈希表中检查是否存在 x − 1 x−1 x1即能判断是否需要跳过了。

增加了判断跳过的逻辑之后,时间复杂度是多少呢?外层循环需要 O ( n ) O(n) O(n)的时间复杂度,只有当一个数是连续序列的第一个数的情况下才会进入内层循环,然后在内层循环中匹配连续序列中的数,因此数组中的每个数只会进入内层循环一次。根据上述分析可知,总时间复杂度为$ O(n)$,符合题目要求。

class Solution {
    public int longestConsecutive(int[] nums) {
        Set<Integer> num_set = new HashSet<Integer>();
        for (int num : nums) {
            num_set.add(num);
        }

        int longestStreak = 0;

        for (int num : num_set) {
            if (!num_set.contains(num - 1)) {
                int currentNum = num;
                int currentStreak = 1;

                while (num_set.contains(currentNum + 1)) {
                    currentNum += 1;
                    currentStreak += 1;
                }

                longestStreak = Math.max(longestStreak, currentStreak);
            }
        }

        return longestStreak;
    }
}

你可能感兴趣的:(LeetCode,leetcode,算法,java)