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.
思路分析:这道题要求O(n)的时间复杂度,因此先排序,再顺序找最长连续这种思路不可行,因为基于比较的排序算法最低时间复杂度是O(nlongn).要想得到O(n)的时间复杂度,需要结合着题的特点,从图的角度思考。可以把数组看成图的结点,连续数字之间存在边,然后进行DFS搜索找到最长的路径。具体做法是,首先把所有数字放入一个hashset,如此可以在常数时间获取一个数以及判定一个数是否存在。然后试图从set中的每个数字开始,向两边搜索相邻的数字,搜索过的数字从set中删除,记录当前搜索的连续子串的长度,并且用maxLen来贪心的保存最大子串长度。如此操作,直到set为空。时间复杂度是O(n)(建set和删除 扫描两次所有元素),空间复杂度也是O(n)。
AC Code
public class Solution {
public int longestConsecutive(int[] num) {
//0241
if(num == null || num.length == 0) return 0;
Set<Integer> set = new HashSet<Integer>();
for(int n : num){
set.add(n);
}
int maxLen = 0;
while(!set.isEmpty()){
Iterator iter = set.iterator();
int curItem = (int) iter.next();
int tempCur = curItem;
int len = 0;
while(set.contains(curItem)){
len++;
set.remove(curItem);
curItem--;
}
curItem = tempCur + 1;
while(set.contains(curItem)){
len++;
set.remove(curItem);
curItem++;
}
if(len > maxLen) maxLen = len;
}
return maxLen;
//0249
}
}