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