题目描述:
给定一个未排序的整数数组,找出最长连续序列的长度。
要求算法的时间复杂度为 O(n)。
题目分析:
大致思路:找到每一个连续序列的首元素,然后求长度,最后返回多个连续序列中最大的长度。
我们可以先将元素去重,然后遍历元素X:
- 若元素X-1在不数组中,则判断以X为首的元素的连续序列的最大长度。
- 否则,continue。
怎么去重呢?
将元素存到Set中!
参考代码:
public int longestConsecutive(int[] nums) {
if(nums == null || nums.length == 0)return 0;
Set<Integer> set = new HashSet<>();
for(Integer num : nums){
set.add(num);
}
int max = 0;
for(Integer num : set){
if(!set.contains(num - 1)){//关键代码
int count = 0;
int temp = num;
while(set.contains(temp)){
count++;
temp++;
}
max = Math.max(max, count);
}
}
return max;
}
注意:思路很重要!!