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;
    }
};
相关推荐
RuiZN15 小时前
UE5 UObject类详解
c++·ue5
ZhangShao060715 小时前
题解:AT_abc459_e
c++
chengO_o15 小时前
AVL树详解与实现(C++)
数据结构·c++·avl树·平衡二叉搜索树
玉树临风ives15 小时前
atcoder ABC 458 题解
数据结构·c++·算法
chengO_o15 小时前
STL关联式容器:map 与 set 的使用
c++·stl·set·map·平衡二叉搜索树
charlie11451419116 小时前
现代C++特性指南(5)——RAII 深入理解:资源管理的基石
开发语言·c++·现代c++
神仙别闹16 小时前
基于QT(C++)+Sqlite3实现单词消除游戏系统
c++·qt·sqlite
yunn_16 小时前
基于C++ 11的线程池实现
c++
人间乄惊鸿客17 小时前
c++自记录
java·开发语言·c++
MC皮蛋侠客17 小时前
C++17 多线程系列(一):线程基础——std::thread 完全指南
开发语言·c++·多线程