[leetcode]128. Longest Consecutive Sequence最长连续序列

it2025-11-26  14

 Given an unsorted array of integers, find the length of the longest consecutive elements sequence.

Your algorithm should run in O(n) complexity.

Example:

Input: [100, 4, 200, 1, 3, 2] Output: 4 Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.

 

题目

给定一个数组,计算将其排序以后能形成的最长连续序列。

 

思路

如果允许O(nlogn)的复杂度,那么可以先排序,可是本题要求O(n)。由于序列里的元素是无序的,又要求O(n),首先要想到用哈希表。用一个哈希表存储所有出现过的元素,对每个元素,以该元素为中心,往左右扩张,直到不连续为止,记录下最长的长度。

 

代码

 

转载于:https://www.cnblogs.com/liuliu5151/p/9828157.html

最新回复(0)