leetcode128 最长连续序列

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

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

示例: 输入: [100, 4, 200, 1, 3, 2]  输出: 4

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

       使用一个集合set存入所有的数字,然后遍历数组中的每个数字,如果其在集合中存在,那么将其移除,然后分别用两个变量pre和next算出其前一个数跟后一个数,然后在集合中循环查找,如果pre在集合中,那么将pre移除集合,然后pre再自减1,直至pre不在集合之中,对next采用同样的方法,那么next-pre-1就是当前数字的最长连续序列,更新res即可。

public int longestConsecutive(int[] nums){
    HashSet<Integer> s = new HashSet<>();
    int res = 0;
    for(int num : nums) s.add(num);
    for(int num : nums){
        if(s.remove(num)){
            int pre = num - 1, next = num + 1;
            while(s.remove(pre)) pre--;
            while(s.remove(next)) next++;
            res = Math.max(res, next - left - 1);
        }
    }
    return res;
}

猜你喜欢

转载自blog.csdn.net/qq_43322057/article/details/84714599