leetcode - 128 最长连续序列

给定一个未排序的整数数组 nums ,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。

请你设计并实现时间复杂度为 O(n) 的算法解决此问题。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/longest-consecutive-sequence
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 

 

自己的解法:先排序后统计!时间复杂度竟然超过97.07%

class Solution {
    public int longestConsecutive(int[] nums) {
        if (nums.length == 0 || nums.length == 1) {
            return nums.length;
        }
        Arrays.sort(nums);
        int max = 1;
        int const_max = 1;
        for (int i  = 0; i < nums.length - 1; i++) {
            max = 1;
            while (i < nums.length - 1 && nums[i + 1] - nums[i] <= 1) {
                if (nums[i + 1] - nums[i] == 1) {
                    max++;
                }
                i++;
            } 
            if (max > const_max) {
                const_max = max;
            }
        }
        return const_max;
    }
}

官方解答:但时间复杂度很高43.88%,好像不是o(n)

class Solution {
    public int longestConsecutive(int[] nums) {
        if (nums.length == 0 || nums.length == 1) {
            return nums.length;
        }
        Set<Integer> set  = new HashSet<>();
        for (int n : nums) {
            set.add(n);
        }
         int longLength = 0;

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

                while (set.contains(currentNum + 1)) {
                    currentNum += 1;
                    currentLength += 1;
                }

                longLength = Math.max(longLength, currentLength);
            }
        }

        return longLength;
    }
}

 

posted @   牵魂  阅读(14)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示