本文共 926 字,大约阅读时间需要 3 分钟。
is:
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.
The most intuitive solution to this problem is sorting the array first, and then go through the sorted array and record the length of the longest consecutive sequence. However, the time complexity of this method is O(nlogn) .
In order to get the O(n) complexity, we can pick up the first element in array(say num[0]
), and then check if num[0]-1
and num[0]+1
are in the array. If yes, iteratively check the upper/lower boundary of this sequence. Until the upper/lower boundaries never change, find a new element in the array that has not been accessed and start a new search.
http://bo-yang.github.io/2014/07/01/longest-consecutive-sequence
转载地址:http://fbpvb.baihongyu.com/