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),首先要想到用哈希表。
用一个哈希表存储所有出现过的元素,对每个元素,以该元素为中心,往左右扩张,直到不连续为止,记录下最长的长度。
代码
扫描二维码关注公众号,回复:
3669646 查看本文章