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;
    }
};
相关推荐
凌康ACG5 小时前
Sciter之c++与前端交互(五)
c++·sciter
郝学胜-神的一滴7 小时前
Linux命名管道:创建与原理详解
linux·运维·服务器·开发语言·c++·程序人生·个人开发
晚风(●•σ )7 小时前
C++语言程序设计——11 C语言风格输入/输出函数
c语言·开发语言·c++
恒者走天下8 小时前
秋招落定,拿到满意的offer,怎么提高自己实际的开发能力,更好的融入团队
c++
天若有情6739 小时前
【c++】手撸C++ Promise:从零实现通用异步回调组件,支持链式调用+异常安全
开发语言·前端·javascript·c++·promise
学困昇9 小时前
C++中的异常
android·java·c++
合作小小程序员小小店10 小时前
桌面安全开发,桌面二进制%恶意行为拦截查杀%系统安全开发3.0,基于c/c++语言,mfc,win32,ring3,dll,hook,inject,无数据库
c语言·开发语言·c++·安全·系统安全
Codeking__10 小时前
C++ 11 atomic 原子性操作
开发语言·c++
crescent_悦10 小时前
PTA L1-020 帅到没朋友 C++
数据结构·c++·算法
卡提西亚10 小时前
C++笔记-34-map/multimap容器
开发语言·c++·笔记