[每日一题]119.最长连续序列

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

举例:

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

Solution

class Solution {
    public int longestConsecutive(int[] nums) {
        if(nums.length == 0){
            return 0;
        }
        // 带记忆化的中心拓展
        Set<Integer> set = new HashSet<>();
        for(int i : nums){
            set.add(i);
        }
        int max = 1;
        for(int i : nums){
            if(set.contains(i)){
                int left = i - 1, right = i + 1, count = 1;
                while(set.contains(left)){
                    set.remove(left);
                    count++;
                    left--;
                }

                while(set.contains(right)){
                    set.remove(right);
                    count++;
                    right++;
                }
                max = Math.max(max, count);
            }
        }
        return max;
    }
}