Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.
You must write an algorithm that runs in O(n) time.
Example 1:
Input: nums = [100,4,200,1,3,2]
Output: 4
Explanation: The longest consecutive elements sequence is [1,2,3,4]. Therefore its length is 4.
Example 2:
Input: nums = [0,3,7,2,5,8,4,6,0,1]
Output: 9
这题的核心是用哈希集合把查找连续性降到 O(1),然后只从“序列起点”开始扩展:当某个数的前一个数不存在时,说明它可能是一个连续段的开头,再向后统计长度即可。这样每个元素最多被处理一次,总时间复杂度可以做到 O(n),也满足题目要求。示例中 [100,4,200,1,3,2] 的最长连续序列是 [1,2,3,4],长度为 4;[0,3,7,2,5,8,4,6,0,1] 则能连成 0 到 8 的完整序列,答案为 9。