class Solution {
public int longestConsecutive(int[] nums) {
// 通过TreeSet在排序数组的同时,过滤数组,使其没有重复数
TreeSet<Integer> set = new TreeSet<>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1 - o2;
}
});
for (int i = 0; i < nums.length; i++) {
set.add(nums[i]);
}
Iterator<Integer> iterator = set.iterator();
// 去除nums中不包含任何元素的情况
if (!iterator.hasNext()) return 0;
int count = 1, max = 1;
int pre = iterator.next();
while (iterator.hasNext()) {
int curr = iterator.next();
// 若满足前一个元素+1等于当前元素,则符合条件,count++,否则,不满足序列条件,重置count
if (curr == pre + 1) {
count++;
} else {
count = 1;
}
pre = curr;
max = Math.max(max, count);
}
return max;
}
}