最长连续序列

最长连续序列

给定一个未排序的整数数组 nums ,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。

请你设计并实现时间复杂度为 O(n) 的算法解决此问题。

在这里插入图片描述

解法1

先对数组进行排序,然后从小到大取最长的连续子串,有以下三种情况

  • 前后两个元素相等,则跳过
  • 前后两个元素不是相邻,重新计数
  • 相邻,计数值+1

时间复杂度: nlogn

class Solution {
public:

    int longestConsecutive(vector<int>& nums) {
        if(nums.size() == 0) return 0;
        sort(nums.begin(), nums.end());
        int t = 1;
        int maxlen = 0;
        for(int i = 0; i < nums.size() - 1; i++) {
            if(nums[i+1] - nums[i] == 0) continue;
            else if(nums[i+1] - nums[i] != 1) {
                maxlen = max(maxlen, t);
                t = 1;
            } 
            else {
                t++;
            }   
        }
        return maxlen>t? maxlen:t;
    }
};

解法2

用哈希表和unorder_set实现

  • 先用unorder_set去重
  • 每一个连续的数都有前缀
  • 若有前缀,则连续,继续判断有多少后缀,记录其长度
class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        unordered_set<int> a;
        for(auto num:nums ) {
            a.insert(num);
        }

        int maxlen;

        for(auto i: a) {
            if(!a.count(i-1)) { //只有有前缀的才能继续判断,否则不连续
                int t = 1;
                int temp = i;
                while(a.count(temp + 1)) {
                    temp++;
                    t++;
                }

                maxlen = max(maxlen, t);
            }
        }
        return maxlen;
    }
};
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值