128. 最长连续序列

发布时间 2023-12-14 15:53:12作者: DawnTraveler

1.题目介绍

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

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

示例 1:

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

示例 2:

输入:nums = [0,3,7,2,5,8,4,6,0,1]
输出:9

提示:

  • \(0 <= nums.length <= 10^{5}\)
  • \(-10^{9} <= nums[i] <= 10^{9}\)

2.题解

2.1 哈希表(unordered_set)

思路

1.首先利用unordered_set对于数组进行去重,得到一个无重复无需set集合。

2.之后最关键的部分来了,虽然我们可以遍历set集合中的每个元素temp,每次用while循环探寻temp+1,+2是否在set集合中,
但最坏情况时间代价还是O(n^2)【外层O(n) ,内层O(n)】,没有明显的改善。
但是如果我们在判断temp的时候,先判断temp-1是否在集合中,若在,说明肯定存在更长的连续序列,跳过此次循环,否则再按上述方法探寻。

外层循环需要 O(n) 的时间复杂度,只有当一个数是连续序列的第一个数的情况下才会进入内层循环,然后在内层循环中匹配连续序列中的数,
因此数组中的每个数只会进入内层循环一次。根据上述分析可知,总时间复杂度为 O(n)

作者:力扣官方题解
链接:https://leetcode.cn/problems/longest-consecutive-sequence/solutions/276931/zui-chang-lian-xu-xu-lie-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

代码

class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        unordered_set<int> ms;
        int ans;
        if (nums.size() != 0) ans = 1;
        else return 0;
        for (auto num: nums){
            ms.insert(num);
        }
        for (auto it = ms.begin(); it != ms.end(); it++){
            int temp = *it, count = 1;
            if (ms.count(temp - 1)) continue;
            while (ms.count(++temp)){
                count++;
            }
            ans = max(ans, count);
        }
        return ans;
    }
};