题目要求时间复杂度为O(n),因此不能使用两次循环匹配。
- 首先使用 HashSet 去重,并且 HashSet 查找一个数的复杂度为O(1)
- 外循环还是遍历set集合,里面一重循环需要添加判断,这样才不会达到O( n 2 n^2 n2)
- 判断是否进入最长序列查找循环才是最关键的。对于 num,如果 num 是最长序列的开始数字,那么 set 集合中一定不存在 num - 1,否则num 就不会是最长序列的开始数字。凭借此逻辑设置 if 条件是关键。
- 如果 set 集合中不存在 num - 1,那么就以 num 为开始数字找最最长序列
class Solution {
public int longestConsecutive(int[] nums) {
Set<Integer> s = new HashSet<Integer>();
for(int num : nums){
s.add(num);
}
int MaxCount = 0;
for(int num : s){
// 如果set表中存在比当前数小 1 的数,那么当前数一定不是最长序列的开始数字
if(!s.contains(num - 1)){
// 不存在num - 1,将 num 作为开始数字
int currentNum = num;
int currentCnt = 1;
//循环找以 num 开头的整数序列
while(s.contains(currentNum + 1)){
currentNum += 1;
currentCnt += 1;
}
MaxCount = Math.max(MaxCount, currentCnt);
}
}
return MaxCount;
}
}