博客
关于我
整数序列中最长的连续序列个数(LeetCode-128)
阅读量:344 次
发布时间:2019-03-04

本文共 1063 字,大约阅读时间需要 3 分钟。

为了解决这个问题,我们需要找到一个整数序列中最长的连续子序列。连续子序列在这里指的是在排序后的序列中,连续递增的数字序列,其中每个数字比前一个大1。

方法思路

  • 排序:首先对序列进行排序。排序可以将所有连续的数字排列在一起,使得后续处理更加容易。
  • 遍历排序后的数组:遍历排序后的数组,统计每个数字与前一个数字的差是否为1。如果是,则当前连续子序列长度加一;否则,重置连续子序列长度为1。
  • 记录最长连续子序列长度:在遍历过程中,记录遇到的最大连续子序列长度。
  • 这种方法的时间复杂度是 O(n log n),因为排序操作的时间复杂度是 O(n log n),而遍历数组的时间复杂度是 O(n),总体复杂度为 O(n log n)。

    解决代码

    #include 
    #include
    using namespace std;int longestConsecutive(vector
    & nums) { if(nums.size() == 0) return 0; sort(nums.begin(), nums.end()); int max_len = 1; int current_len = 1; for(int i = 1; i < nums.size(); ++i) { if(nums[i] == nums[i-1] + 1) { current_len++; } else { current_len = 1; } if(current_len > max_len) { max_len = current_len; } } return max_len;}

    代码解释

  • 检查空序列:首先检查序列是否为空,如果为空,返回0。
  • 排序:对序列进行排序,使得连续的数字相邻排列。
  • 初始化变量max_len 记录最长连续子序列长度,current_len 记录当前连续子序列长度。
  • 遍历数组:从第二个元素开始,检查当前元素与前一个元素是否连续递增。如果是,则增加当前连续子序列长度;否则,重置长度为1。
  • 更新最大长度:在每次遍历后,更新最长连续子序列长度。
  • 返回结果:返回最长连续子序列的长度。
  • 这种方法通过排序和遍历,能够高效地解决问题,确保在合理的时间复杂度内完成任务。

    转载地址:http://tbqe.baihongyu.com/

    你可能感兴趣的文章
    TCP基本入门-简单认识一下什么是TCP
    查看>>
    tableviewcell 中使用autolayout自适应高度
    查看>>
    Symbolic Aggregate approXimation(SAX,符号聚合近似)介绍-ChatGPT4o作答
    查看>>
    Orcale表被锁
    查看>>
    svn访问报错500
    查看>>
    sum(a.YYSR) over (partition by a.hy_dm) 不需要像group by那样需要分组函数。方便。
    查看>>
    Orderer节点启动报错解决方案:Not bootstrapping because of 3 existing channels
    查看>>
    sqlserver学习笔记(三)—— 为数据库添加新的用户
    查看>>
    org.apache.ibatis.exceptions.PersistenceException:
    查看>>
    org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned
    查看>>
    org.apache.ibatis.type.TypeException: Could not resolve type alias 'xxxx'异常
    查看>>
    org.apache.poi.hssf.util.Region
    查看>>
    org.apache.xmlbeans.XmlOptions.setEntityExpansionLimit(I)Lorg/apache/xmlbeans/XmlOptions;
    查看>>
    org.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss for /
    查看>>
    org.hibernate.HibernateException: Unable to get the default Bean Validation factory
    查看>>
    org.hibernate.ObjectNotFoundException: No row with the given identifier exists:
    查看>>
    SQL-CLR 类型映射 (LINQ to SQL)
    查看>>
    org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
    查看>>
    org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
    查看>>
    org.springframework.web.multipart.MaxUploadSizeExceededException: Maximum upload size exceeded
    查看>>