Longest Consecutive Sequence

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值