Leetcode128 最长连续序列

Leetcode128 最长连续序列_第1张图片

#HashSet查找复杂度为O(1)
#找最长连续序列只需要从不存在比自己-1的数字开始找即可
class Solution {
    public int longestConsecutive(int[] nums) {
        Set set = new HashSet<>();
        for(int num : nums){
            set.add(num);
        }
        int LongestAns = 0;
        for(Integer num : set){
            if(!set.contains(num - 1)){
                int CurrentNum = num;
                int CurrentAns = 1;
                while(set.contains(CurrentNum + 1)){
                    CurrentNum ++;
                    CurrentAns ++;
                }
                LongestAns = Math.max(LongestAns, CurrentAns);
            }
           
        }
        return LongestAns;
    }
}

你可能感兴趣的:(算法,java,数据结构)