LeetCode 128. 最长连续序列

LeetCode 128. 最长连续序列,第1张

Description:

题目大意:给出一个数组,找到最长的连续数字序列。

解题思路:

算法标签:哈希表

  1. 利用 unordereds_set 将所有元素加入,去重,不需要排序
  2. 对每个元素依次遍历,前面的元素不存在再访问,因为那样才不连续
代码:
class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        // 速度更快
        unordered_set<int>number;
        for(int i = 0;i < nums.size();i++) 
            number.insert(nums[i]);
        int ans = 0;

        for(const int& num : number) {
            // 前面的数字必须不存在,不然就连在一起了
            if(!number.count(num - 1)) {
                int currenttnum = num;
                int currentlength = 1;

                while(number.count(currenttnum + 1)) {
                    currenttnum += 1;
                    currentlength += 1;
                }

                ans = max(ans , currentlength);
            }
        }
        return ans;
    }
};

欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/langs/713758.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-24
下一篇 2022-04-24

发表评论

登录后才能评论

评论列表(0条)

保存