今天遇到一个比较容易的题,leetCode地址
给定一个未排序的整数数组,找出最长连续序列的长度。
要求算法的时间复杂度为 O(n)。
示例:
输入: [100, 4, 200, 1, 3, 2]
输出: 4
解释: 最长连续序列是 [1, 2, 3, 4]。它的长度为 4。
我想到的是先排序,再遍历排序后的数组。排序O(logn)的算法,比如归并排序或快排,算法详情地址。遍历数组,时间复杂度为O(n)。
官方题解给了另外一种思路
public int longestConsecutive(int[] nums) {
Set<Integer> set = new HashSet<Integer>();
for(int item : nums){
set.add(item);
}
int res = 0;
for(int i =0; i < nums.length; i++){
if(!set.contains(nums[i] - 1)){ // 找到序列开关元素
int current = nums[i];
int len = 1;
while(set.contains(++current)){ // 含有比它大1的元素
len++;
}
res = Math.max(res, len);
}
}
return res;
}
数组元素放入set中,可快速判断,一个数字,其相邻数字是否存在。利用这一点,就可以解开题目啦!