Leetcode 128 最长连续序列

地址 https://leetcode-cn.com/problems/longest-consecutive-sequence/

给定一个未排序的整数数组,找出最长连续序列的长度。

要求算法的时间复杂度为 O(n)。

示例:

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

解法

这个题目作为困难难度有点疑惑。

使用双指针找到连续长度即可。 考虑到例外情况就是可能会有多个相同数字

那么l作为起点 r作为终点,使用滑动窗口,每次r比r-1的数字等于或者大1 那么r向右移动。等于的时候答案不增加,r比r-1的数字 大1时候答案增加。

若发现r不连续了 则l将此时的r作为起点,继续滑动窗口算法。

class Solution {
public:

    int longestConsecutive(vector<int>& nums) {
    if (nums.size() < 2) return nums.size();
    sort(nums.begin(), nums.end());
    int ans = 1;
    int l = 0; int r = l ;
    while (l <= r && l < nums.size() && r < nums.size())
    {
        int count = 1; r = l + 1;
        while (r < nums.size() && (nums[r] == nums[r - 1] || nums[r] == nums[r - 1] + 1))
        {
            if (nums[r] == nums[r - 1] + 1) count++;
            r++;
        }

        ans = max(ans, count);
        l = r ;
    }

    return ans;
}
    
};

另外一种做法是 使用哈希记录数组中的 数字 然后统计连续数组的长度

相当于在哈希表上做类似滑动窗口的操作

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

        int longestStreak = 0;

        for (const int& num : num_set) {
            if (!num_set.count(num - 1)) {
                int currentNum = num;
                int currentStreak = 1;

                while (num_set.count(currentNum + 1)) {
                    currentNum += 1;
                    currentStreak += 1;
                }

                longestStreak = max(longestStreak, currentStreak);
            }
        }

        return longestStreak;           
    }
};
作 者: itdef
欢迎转帖 请保持文本完整并注明出处
技术博客 http://www.cnblogs.com/itdef/
B站算法视频题解
https://space.bilibili.com/18508846
qq 151435887
gitee https://gitee.com/def/
欢迎c c++ 算法爱好者 windows驱动爱好者 服务器程序员沟通交流
如果觉得不错,欢迎点赞,你的鼓励就是我的动力
阿里打赏 微信打赏
原文地址:https://www.cnblogs.com/itdef/p/13056351.html