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

128:最长连续序列

作者: nobigogle | 来源:发表于2022-03-19 19:21 被阅读0次

题意

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

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

example

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

解析

求出连续的最长序列,首先用HashSet保存所有值,遍历HashSet,当前元素不是序列的最小值时,直接跳过,当是最小值时,再进行个数统计。

实现

class Solution {
    public int longestConsecutive(int[] nums) {
        if(nums==null||nums.length==0) return 0;
        // 保存Set方便快速检索
        HashSet<Integer> hashSet = new HashSet<Integer>();
        for(int i = 0;i<nums.length;i++){
            hashSet.add(nums[i]);
        }
        int ans = 1;
        for(int num:nums){
            if(hashSet.contains(num-1)) continue;
            int current = num;
            int number = 1;
            while(hashSet.contains(current+1)){
                current++;
                number++;
            }
            if(number>ans) ans = number;
        }
        return ans;
    }
}

相关文章

  • LeetCode-128-最长连续序列

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

  • 128:最长连续序列

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

  • Leetcode并查集

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

  • leetcode每日一题

    3/24 128 最长连续序列 本题基本的算法思想是并查集与哈希表len[i]存储数字i所在的最长连续序列,但其实...

  • 128. 最长连续序列

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

  • 128. 最长连续序列

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

  • 128. 最长连续序列

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

  • 128. 最长连续序列

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

  • 128. 最长连续序列

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

  • 128. 最长连续序列

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

网友评论

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

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