美文网首页
128. 最长连续序列

128. 最长连续序列

作者: 名字是乱打的 | 来源:发表于2021-10-22 00:27 被阅读0次

题目:

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

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

      
示例 1:

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

思路:

  • 1.先用set去一次重
  • 2.遍历Set的时候判断一下当前数字是否是Set里连续数字的最小数
  • 3.我们只从最小数进行寻找,找比自己大1的连续数,直到找不到为止

代码:

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;
    }

相关文章

  • LeetCode-128-最长连续序列

    LeetCode-128-最长连续序列 128. 最长连续序列[https://leetcode-cn.com/p...

  • Leetcode并查集

    128. 最长连续序列[https://leetcode-cn.com/problems/longest-cons...

  • LeetCode 128. 最长连续序列 | Python

    128. 最长连续序列 题目 给定一个未排序的整数数组,找出最长连续序列的长度。 要求算法的时间复杂度为 O(n)...

  • 128. 最长连续序列

    128. 最长连续序列 给定一个未排序的整数数组,找出最长连续序列的长度。 要求算法的时间复杂度为 O(n)。 示...

  • 128. 最长连续序列

    原题 https://leetcode-cn.com/problems/longest-consecutive-s...

  • 128. 最长连续序列

    https://leetcode-cn.com/problems/longest-consecutive-sequ...

  • 128. 最长连续序列

    解题思路 排序+去重 那么这个题目的时间复杂度是O(N^2) 首先去重, 这里使用unordered_set<> ...

  • 128. 最长连续序列

    题目描述 给定一个未排序的整数数组,找出最长连续序列的长度。要求算法的时间复杂度为 O(n)。 解题思路 直接能想...

  • 128. 最长连续序列

    给定一个未排序的整数数组,找出最长连续序列的长度。 要求算法的时间复杂度为 O(n)。 示例: 输入: [100,...

  • 128. 最长连续序列

    题目: 思路: 1.先用set去一次重 2.遍历Set的时候判断一下当前数字是否是Set里连续数字的最小数 3.我...

网友评论

      本文标题:128. 最长连续序列

      本文链接:https://www.haomeiwen.com/subject/stnfaltx.html