[算法]LeetCode每日一题--128最长连续序列

DailyChallenge

128. 最长连续序列

Hard20200606

Description

给定一个未排序的整数数组,找出最长连续序列的长度。

要求算法的时间复杂度为 O(n)。

示例一

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

Solution

虑枚举数组中的每个数 xx,考虑以其为起点,不断尝试匹配 x+1, x+2, ⋯ 是否存在,假设最长匹配到了x+y,那么以x为起点的最长连续序列即为x, x+1, x+2,⋯,x+y,其长度为y+1,不断枚举并更新答案即可。

从 x−1 开始尝试匹配,因此我们每次在哈希表中检查是否存在 x−1 即能判断是否需要跳过了。

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

你可能感兴趣的:(算法)