力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
给定一个未排序的整数数组
nums,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。请你设计并实现时间复杂度为
O(n)的算法解决此问题。
题解:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
代码:
class Solution {
    public int longestConsecutive(int[] nums) {
        Set<Integer> set = new HashSet<>();
        for(int num : nums){
            set.add(num);
        }
        int res = 0;
        for(int num : set) {
            int cur = num;
            if(!set.contains(cur-1)){
                while(set.contains(cur+1)){
                    cur++;
                }
            }
            res = Math.max(res, cur - num + 1);
        }
        return res;
    }
} 




















