leetcode(hot100)3

解题思路:本题用的是unordered_set,只需要集合就行 set存储的数据不能重复,将所有的数据都存储在set中,然后寻找验证它是不是开头(通过寻找num-1),然后验证它的下一个数存不存在,存在结果就加一,数字也加一,不存在就跳过。

cpp 复制代码
class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        unordered_set<int>set(nums.begin(),nums.end());
        int sum = 0;
        for(int num : set){
            if(!set.count(num-1)){
                int currentnum = num;
                int currentstack = 1;
                while(set.count(currentnum + 1)){
                    currentnum += 1;
                    currentstack += 1;
                }
                sum = max(currentstack,sum);
            }
        }
        return sum;
    }
};
相关推荐
sjsjs113 小时前
力扣3558. 给边赋权值的方案数 I
算法·leetcode·职场和发展
花间相见3 小时前
【LeetCode01】—— 无重复字符的最长子串:滑动窗口经典题详解
python·算法·leetcode
言存4 小时前
力扣热题283 移动零
数据结构·算法·leetcode
ywl4708120875 小时前
‌HashMap 1.8 的扩容机制(Resize)‌
算法·哈希算法
洛水水6 小时前
【力扣100题】80.寻找旋转排序数组中的最小值
数据结构·算法·leetcode
洛水水7 小时前
【力扣100题】82.有效的括号
c++·算法·leetcode
legend050709ComeON7 小时前
常见面试题-leetcode
数据结构·算法·leetcode
Lsk_Smion8 小时前
力扣实训 _ [207].课程表/图论
数据结构·leetcode·图论
风筝在晴天搁浅8 小时前
LeetCode CodeTop 88.合并两个有序数组
算法·leetcode·职场和发展