Longest Consecutive Sequence
2016-07-05 01:48
363 查看
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
Clarification
Your algorithm should run in O(n) complexity.
Example
Given
The longest consecutive elements sequence is
分析:
既然要求O(n) complexity,排序这种方法就放弃了。这里用了HashSet来保存每个数,然后从这个数开始,左右寻找是否有相邻的数。非常有新意的方法。
参考请注明出处:cnblogs.com/beiyeqingteng/
Clarification
Your algorithm should run in O(n) complexity.
Example
Given
[100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is
[1, 2, 3, 4]. Return its length:
4.
分析:
既然要求O(n) complexity,排序这种方法就放弃了。这里用了HashSet来保存每个数,然后从这个数开始,左右寻找是否有相邻的数。非常有新意的方法。
public class Solution { public int longestConsecutive(int[] num) { if (num == null || num.length == 0) return 0; HashSet<Integer> hs = new HashSet<Integer>(); for (int i = 0; i < num.length; i++) { hs.add(num[i]); } int max = 0; for (int i = 0; i < num.length; i++) { if (hs.contains(num[i])) { int count = 1; hs.remove(num[i]); int low = num[i] - 1; while (hs.contains(low)) { hs.remove(low); low--; count++; } int high = num[i] + 1; while (hs.contains(high)) { hs.remove(high); high++; count++; } max = Math.max(max, count); } } return max; } }
参考请注明出处:cnblogs.com/beiyeqingteng/
相关文章推荐
- HTML标签marquee实现滚动效果
- APUE(5)---标准I/O库 (3)
- JS与HTML结合使用marquee标签实现无缝滚动效果代码
- UIScrollView截取内部内容存入相册
- UIPickerView
- iOS第三方左对齐布局类——UICollectionViewLeftAlignedLayout
- 使用Storyboard时出现以下警告:Scene is unreachable due to lack of entry points and does not have an identifier
- sqlite错误处理:library routine called out of sequence
- 第三十四篇:在SOUI中使用异步通知
- Android系统应用---SystemUI之二:Statusbar显示流程以及系统状态图标更新分析
- 微软极品工具箱-Sysinternals Suite
- UIScrollView增加刷新
- CDMA系统的UIM卡介绍 ,IMSI,ESN,MDN
- 消息队列(Message Queue)简介及其使用
- uuid_short() 源代码
- Android酷炫实用的开源框架(UI框架)
- 非GUI-Qt程序运行后显示Console(简单好用)
- deque 迭代器失效的问题详解
- The current branch is not configured for pull No value for key branch.master.merge found in configur
- NSOperationQueue队列