最长连续序列

给定一个未排序的整数数组,找出最长连续序列的长度。

要求算法的时间复杂度为 O(n)。

示例:

输入: [100, 4, 200, 1, 3, 2]
输出: 4
解释: 最长连续序列是 [1, 2, 3, 4]。它的长度为 4。

解题:
一开始应该想到的是暴力法,将nums中的元素放到一个set中,在nums数组依次找nums[i]的元素的nums[i]+1是不是在set中,如果在,则,count加一,最后取max,结束,收功

class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        if(nums.empty()){
            return 0;
        }
        unordered_set<int>myset(nums.begin(),nums.end());
        int res = 0;
        for(auto num:nums){
            int count=0;
            while(myset.count(num)){
                count++;
                num++;
            }
            res = max(res,count);
        }
        return res;
    }
};

当然这种解法肯定是不符合题意的,我们要做优化,其中,因为我们要找最长的连续数字。所以如果是数组 54367,当我们遇到 5 的时候计算一遍 567。遇到 4 又计算一遍 4567。遇到 3 又计算一遍 34567。很明显从 3 开始才是我们想要的序列。
换句话讲,我们只考虑从序列最小的数开始即可。实现的话,当考虑 n 的时候,我们先看一看 n - 1 是否存在,如果不存在,那么从 n 开始就是我们需要考虑的序列了。否则的话,直接跳过

class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        if(nums.empty()){
            return 0;
        }
        unordered_set<int>myset(nums.begin(),nums.end());
        int res = 0;
        for(auto num:nums){
            int count=0;
            if(!myset.count(num-1)){//直接跳过存在n-1的情况,从没有更小的数开始,也就死从最小的数开始;
                while(myset.count(num)){
                    count++;
                    num++;
                }
            }
            res = max(res,count);
        }
        return res;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值