Longest Consecutive Sequence
Posted 北叶青藤
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Longest Consecutive Sequence相关的知识,希望对你有一定的参考价值。
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来保存每个数,然后从这个数开始,左右寻找是否有相邻的数。非常有新意的方法。
1 public class Solution { 2 3 public int longestConsecutive(int[] num) { 4 if (num == null || num.length == 0) return 0; 5 6 HashSet<Integer> hs = new HashSet<Integer>(); 7 for (int i = 0; i < num.length; i++) { 8 hs.add(num[i]); 9 } 10 11 int max = 0; 12 for (int i = 0; i < num.length; i++) { 13 if (hs.contains(num[i])) { 14 int count = 1; 15 hs.remove(num[i]); 16 17 int low = num[i] - 1; 18 while (hs.contains(low)) { 19 hs.remove(low); 20 low--; 21 count++; 22 } 23 24 int high = num[i] + 1; 25 while (hs.contains(high)) { 26 hs.remove(high); 27 high++; 28 count++; 29 } 30 max = Math.max(max, count); 31 } 32 } 33 return max; 34 } 35 }
参考请注明出处:cnblogs.com/beiyeqingteng/
以上是关于Longest Consecutive Sequence的主要内容,如果未能解决你的问题,请参考以下文章
LC.298.Binary Tree Longest Consecutive Sequence