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 [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 == ) return ; HashSet<Integer> hs = new HashSet<Integer>();
for (int i = ; i < num.length; i++) {
hs.add(num[i]);
} int max = ;
for (int i = ; i < num.length; i++) {
if (hs.contains(num[i])) {
int count = ;
hs.remove(num[i]); int low = num[i] - ;
while (hs.contains(low)) {
hs.remove(low);
low--;
count++;
} int high = num[i] + ;
while (hs.contains(high)) {
hs.remove(high);
high++;
count++;
}
max = Math.max(max, count);
}
}
return max;
}
}

参考请注明出处:cnblogs.com/beiyeqingteng/

最新文章

  1. 详细介绍Mysql各种存储引擎的特性以及如何选择存储引擎
  2. 2-Sat问题
  3. 76 mkswaP-用于设置交换区
  4. jQuery学习笔记--JqGrid相关操作 方法列表(上)
  5. android 照片地理位置 demo
  6. 使用 MNIST 图像识别数据集
  7. Android 再按一次退出程序
  8. 设置JVM内存溢出时快照转存HeapDump到文件
  9. /root/.bashrc与/etc/profile的异同
  10. Exynos4412交叉编译环境搭建
  11. 深度优先搜索(DFS)与广度优先搜索(BFS)的Java实现
  12. 控制可编辑的Div 在添加图片,或者@某人的时候 光标移动到最后
  13. 技术分享:RxJS实战练习-经典游戏Breakout
  14. 异常处理与网络基础中的tcp,udp协议
  15. Can peel peel solve pesticide problem
  16. 代码阅读笔记:【C-COT】
  17. 批处理(.bat脚本)基本命令语法
  18. 20155326刘美岑2016-2017-2《Java程序设计》第三周学习总结
  19. 用户数以及psp
  20. Educational Codeforces Round 54 (Rated for Div. 2) Solution

热门文章

  1. foeach集合遍历
  2. 部署搭建 Saltstack(centos6.6)
  3. 更改动软代码生成器模板 验证Model数据合法性
  4. hdu 1205 吃糖果
  5. dedecms首页调用栏目内容和单页内容的方法
  6. pthread_cancel
  7. CSS 仿Excel表格功能
  8. spring mvc实现新增用户
  9. java gc的工作原理、如何优化GC的性能、如何和GC进行有效的交互
  10. ngrok反向代理