一个通过 Python 找到最长连续序列长度的程序


假设我们有一个无序的数字数组,我们必须找到连续元素的最长序列长度。

因此,如果输入类似于 nums = [70, 7, 50, 4, 6, 5],则输出将为 4,因为连续元素的最长序列是 [4, 5, 6, 7]。因此,我们返回其长度:4。

为了解决这个问题,我们将遵循以下步骤 −

  • nums := nums 的所有唯一元素

  • max_cnt := 0

  • 对于 nums 中的每个 num,执行以下操作:

    • 如果 num - 1 不在 nums 中,则

      • cnt := 0

      • 当 num 存在于 nums 中时,执行以下操作:

        • num := num + 1

        • cnt := cnt + 1

      • max_cnt := max_cnt 和 cnt 的最大值

  • 返回 max_cnt

让我们看看以下实现以获得更好的理解 −

示例

 在线演示

class Solution:
   def solve(self, nums):
      nums = set(nums)
      max_cnt = 0
      for num in nums:
         if num - 1 not in nums:
            cnt = 0
            while num in nums:
               num += 1
               cnt += 1
            max_cnt = max(max_cnt, cnt)
      return max_cnt
ob = Solution()
nums = [70, 7, 50, 4, 6, 5]
print(ob.solve(nums))

输入

[70, 7, 50, 4, 6, 5]

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

输出

4

更新于: 10-10-2020

713 次浏览

开启您的 职业生涯

完成课程,获得认证

立即开始
广告