题目链接:https://leetcode.cn/problems/longest-consecutive-sequence/
难度:中等

描述:
给定一个未排序的整数数组 nums ,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。
请你设计并实现时间复杂度为 O(n) 的算法解决此问题。

提示:
nums.length:[0, 100000]

题解

  1. class Solution:
  2. def longestConsecutive(self, nums: List[int]) -> int:
  3. ret = 0
  4. s = set(nums)
  5. for num in nums:
  6. if num - 1 not in s:
  7. cur = num
  8. temp_length = 1
  9. while cur + 1 in s:
  10. temp_length += 1
  11. cur += 1
  12. ret = max(ret, temp_length)
  13. return ret