题干
给定一个未排序的整数数组,找出最长连续序列的长度。
要求算法的时间复杂度为 O(n)。
示例:
输入: [100, 4, 200, 1, 3, 2]
输出: 4
解释: 最长连续序列是 [1, 2, 3, 4]。它的长度为 4。
想法
看示例发现这个连续序列和原本数组的整数的位置没有关系。
也就是说数组最大的好处 随机访问没有了 也就是说这个数组仅仅是给值的作用
那我可以把数组的值存入hashset,后续再访问就很方便了。
存入hashset后遍历set
如果遍历到的这个num-1不存在于set,也就是说它可以作为连续序列的起点,那就继续检验num+1在不在set,因为set查找是0(1)所以非常方便
Java代码
package daily;
import java.util.HashSet;
import java.util.Set;
public class LongestConsecutive {
public int longestConsecutive(int[] nums) {
//set存所有num
Set<Integer> set = new HashSet<>();
//res存最长长度
int res = 0;
//set存入
for (int n : nums
) {
set.add(n);
}
//遍历set
for (int num : set
) {
//如果num可以作为起点
if (!set.contains(num - 1)) {
int current_num = num;
int now_consective = 1;
//res最大可以是
while (set.contains(current_num + 1)) {
current_num++;
now_consective++;
}
res = Math.max(res, now_consective);
}
}
return res;
}
public static void main(String[] args) {
LongestConsecutive longestConsecutive = new LongestConsecutive();
int[] nums = {100, 4, 200, 1, 3, 2};
System.out.println(longestConsecutive.longestConsecutive(nums));
}
}