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;
    }
};
相关推荐
张张努力变强37 分钟前
C++ STL string 类:常用接口 + auto + 范围 for全攻略,字符串操作效率拉满
开发语言·数据结构·c++·算法·stl
小镇敲码人41 分钟前
探索CANN框架中TBE仓库:张量加速引擎的优化之道
c++·华为·acl·cann·ops-nn
平安的平安1 小时前
面向大模型算子开发的高效编程范式PyPTO深度解析
c++·mfc
June`1 小时前
muduo项目排查错误+测试
linux·c++·github·muduo网络库
C++ 老炮儿的技术栈1 小时前
VS2015 + Qt 实现图形化Hello World(详细步骤)
c语言·开发语言·c++·windows·qt
Once_day1 小时前
C++之《Effective C++》读书总结(4)
c语言·c++·effective c++
柯一梦1 小时前
STL2---深入探索vector的实现
c++
MSTcheng.1 小时前
【C++】C++11新特性(二)
java·开发语言·c++·c++11
愚者游世1 小时前
Delegating Constructor(委托构造函数)各版本异同
开发语言·c++·程序人生·面试·改行学it
小镇敲码人1 小时前
探索华为CANN框架中的ACL仓库
c++·python·华为·acl·cann