用 Python 编写的查找最长连续序列长度的程序
pythonserver side programmingprogramming更新于 2026/1/23 20:28:17
假设我们有一个未排序的数字数组,我们必须找到最长连续元素序列的长度。
因此,如果输入为 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]
输出
4
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

