LeetCode #128 Longest Consecutive Sequence

题目:

Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
For example,
Given [100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.
Your algorithm should run in O(n) complexity.

 

分析:

给定一个数组,求该数组中的数字所能构成的最长连续数列的长度。要求时间复杂度为O(n)。

我们使用HashMap。其中key为数组中的数字;value为该数字作为某个连续数列的边界时,该数列的长度。例如,对于数列{1,2,3,4,5},该数列的边界时1和5,那么在HashMap中1和5对应的value都是该数列的长度5。

当我们新读取一个数字时,该数字可能和其左侧或右侧的某个连续数列连接在一起。通过读取HashMap中 n-1 和 n+1 对应的value即可获得左侧和右侧连续数列的长度。之后将它们连接在一起,构成了一个新的更长的数列。最后将新数列边界元素的value更新为新的长度即可。

 

代码:

Java

 


参考文章:

https://leetcode.com/discuss/18886/my-really-simple-java-o-n-solution-accepted