Longest Consecutive Sequence

来源:互联网 发布:男士便宜单肩包 知乎 编辑:程序博客网 时间:2024/05/22 10:39

The problem 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.

- See more at:http://bo-yang.github.io/2014/07/01/longest-consecutive-sequence/#sthash.bMRBG42u.dpuf

http://bo-yang.github.io/2014/07/01/longest-consecutive-sequence

0 0
原创粉丝点击