力扣 128. 最长连续序列(困难难度)

力扣 128. 最长连续序列(困难难度)

题目:给定一个未排序的整数数组,找出最长连续序列的长度。
要求算法的时间复杂度为 O(n)。

示例:
输入: [100, 4, 200,1, 3, 2]
输出: 4
解释: 最长连续序列是 [1, 2, 3, 4]。它的长度为 4。

思路:将数组放入Hash表中,然后通过contains的方法对数字的连续性进行验证。这里为了使时间复杂度减小,我们这里只要对连续数列的第一个进行操作。

代码如下

class Solution {
    public int longestConsecutive(int[] nums) {
        int maxLength=0;
        Set<Integer> set=new HashSet<Integer>();
        for(int num:nums){
            set.add(num);
        }
        for(int num:set){
            if(set.contains(num-1)){
                continue;
            }else{
                int currentLength=1;
                int currentNum=num;
                while(set.contains(currentNum+1)){
                    currentLength++;
                    currentNum++;
                }
                maxLength=Math.max(currentLength,maxLength);
            }
        }
        return maxLength;
    }
}

你可能感兴趣的:(leetcode)