128. 最长连续序列

2021-10-22  本文已影响0人  名字是乱打的

题目:

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

请你设计并实现时间复杂度为 O(n) 的算法解决此问题。

      
示例 1:

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

思路:

代码:

public int longestConsecutive(int[] nums) {
        int len=nums.length;
        if (len<1){
            return len;
        }

        Set<Integer> numSet=new HashSet<>();
        for (int num : nums) {
            numSet.add(num);
        }

        int res=0;

        for (Integer curr : numSet) {
            //如果当前数字已是连续数字的最小数
            if (!numSet.contains(curr-1)){
                int currLength=1;
                int nextSearchNum=curr+1;
                while (numSet.contains(nextSearchNum)){
                    currLength++;
                    nextSearchNum++;
                }
                
                res=Math.max(res, currLength);
            }
        }
        return res;
    }
上一篇 下一篇

猜你喜欢

热点阅读