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;
    }
};
相关推荐
feng_you_ying_li1 小时前
c++之哈希表的介绍与实现
开发语言·c++·散列表
xh didida1 小时前
C++ -- string
开发语言·c++·stl·sring
m晴朗2 小时前
测试覆盖率从35%到80%:我用AI批量生成C++单元测试的完整方案
c++·gpt·ai
无限进步_2 小时前
【C++&string】大数相乘算法详解:从字符串加法到乘法实现
java·开发语言·c++·git·算法·github·visual studio
苏纪云2 小时前
蓝桥杯考前突击
c++·算法·蓝桥杯
‎ദ്ദിᵔ.˛.ᵔ₎2 小时前
模板template
开发语言·c++
charlie1145141912 小时前
通用GUI编程技术——图形渲染实战(二十九)——Direct2D架构与资源体系:GPU加速2D渲染入门
开发语言·c++·学习·架构·图形渲染·win32
小肝一下2 小时前
每日两道力扣,day8
c++·算法·leetcode·哈希算法·hot100
CheerWWW3 小时前
C++学习笔记——线程、计时器、多维数组、排序
c++·笔记·学习
无限进步_3 小时前
【C++】验证回文字符串:高效算法详解与优化
java·开发语言·c++·git·算法·github·visual studio