Leetcode128. 最长连续序列(HOT100)

链接

第一次错误提交:

cpp 复制代码
class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        int n = nums.size();
        int res = 0;
        sort(nums.begin(),nums.end());//第一次错误写作:sort(nums,nums+n);nums是std::vector<int>类型,不能与int相加,这不是普通数组,不能这样写
        for(int i = 0;i<n;){
            int j = i+1;
            int count = 1;
            while(j<n){
                if(nums[j]==nums[j-1]){
                    ++j;
                }
                else if(nums[j]==nums[j-1]+1){
                    count++;
                    j++;
                }
                else{ 
                    res = max(res,count);
                    break;
                }
            }                   

            i = j;
        }
        return res;
    }
};

错误原因是:我把res的更新放在了while里边,这存在一个问题:只有出现 1 3这种差距超过1时res才会更新,那么如果数组长这样:1 2 3 4 5,我就永远不会更新res了,res永远是0,当j 走过n时跳出去......同理,i = j; 这一句也不应该放在里边,否则i 将很难更新,导致超时。

第二次正确提交:

cpp 复制代码
class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        int n = nums.size();
        int res = 0;
        sort(nums.begin(),nums.end());
        for(int i = 0;i<n;){
            int j = i+1;
            int count = 1;
            while(j<n){
                if(nums[j]==nums[j-1]){
                    ++j;
                }
                else if(nums[j]==nums[j-1]+1){
                    count++;
                    j++;
                }
                else{ 
                    break;
                }
            }                   
            res = max(res,count);
            i = j;
        }
        return res;
    }
};

使用了unordered_set的方法,正确提交,因为重复元素对于本题没有意义,所以去重刚好满足要求。

cpp 复制代码
class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        unordered_set<int> s;
        int res =  0;
        for(const auto&e:nums){
            s.insert(e);
        }
        for(const auto& e:nums){
            if(s.count(e)&&!s.count(e-1)){
                s.erase(e);
                int u = e+1;
                while(s.count(u)){
                    s.erase(u);
                    ++u;
                }
                res = max(res,u-e);
            }
        }
        return res;
    }
};
相关推荐
Je1lyfish1 小时前
CMU15-445 (2025 Fall/2026 Spring) Project#3 - QueryExecution
linux·c语言·开发语言·数据结构·数据库·c++·算法
Brilliantwxx1 小时前
【C++】 vector(代码实现+坑点讲解)
开发语言·c++·笔记·算法
叼烟扛炮2 小时前
C++第三讲:类和对象(中)
开发语言·c++·类和对象
KuaCpp2 小时前
C++新特性学习
c++·学习
墨染千千秋3 小时前
C/C++ Keywords
c语言·c++
ximu_polaris3 小时前
设计模式(C++)-行为型模式-中介者模式
c++·设计模式·中介者模式
CSCN新手听安4 小时前
【Qt】Qt窗口(八)QFontDialog字体对话框,QInputDialog输入对话框的使用,小结
开发语言·c++·qt
tumu_C5 小时前
用std::function减缓C++模板代码膨胀和编译压力的一个场景
开发语言·c++
Hical616 小时前
C++17 实战心得:那些真正改变我写代码方式的特性
c++
Hical616 小时前
实测:C++20 协程 vs Go Gin vs Rust Actix,谁的 Web 性能更强?
c++