
java
class Solution {
public int longestConsecutive(int[] nums) {
Set<Integer> set = new HashSet<>();
//将数组中的数字存到set集合中
for(int num : nums){
set.add(num);
}
int longestStreak = 0;
//挨个数字检查
for(int num : set){
//从set集合中查是否有该比该数字小的数字,如果没有,作为开头开始继续往后找
if(!set.contains(num - 1)){
int currentNum = num;
int currentStreak = 1;
while(set.contains(currentNum + 1)){
currentNum += 1;
currentStreak += 1;
}
longestStreak = Math.max(longestStreak,currentStreak);
}
}
return longestStreak;
}
}
先挨个数字检查能作为头元素的数字,找到头元素后,开始找头元素连续的后续元素。