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

128. 最长连续序列

作者: geaus | 来源:发表于2020-06-06 19:27 被阅读0次

题目描述

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

示例:

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

解题思路

直接能想到的方式是,先对数组进行排序,然后从头遍历数组找到最长的连续序列,但这样算法复杂度是O(nlogn)。
另外一种思路是,将数组转为hash set,对set中的每个数连续判断num+1,num+2...是否存在,每次访问存在O(1)。但是有个问题需要避免,存在重复判断。所以在访问set的某个数时,需要判断num-1是否存在,如果存在则说明遍历num-1时已经访问num,所以这里就不需要继续访问num。这样的时间复杂度为O(n)。


class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        unordered_set<int> nums_set;
        for(int val : nums){
            nums_set.insert(val);
        }

        int ret = 0;
        for(int val : nums_set){
            if(!nums_set.count(val-1)){
                int current_length = 1;
                int current_num = val;
                while(nums_set.count(current_num+1)){
                    current_length += 1;
                    current_num += 1;
                }

                ret = ret>current_length ? ret:current_length;
            }
        }

        return ret;
    }
};

相关文章

  • 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/bndftktx.html