显然是不能使用比较排序的,然后还要设计到去重的问题,于是使用set了,于是想到使用TreeSet,一键解决美滋滋,不过比较恼人的是不能进行索引遍历,所以还得先复制到一个数组里去
public int longestConsecutive(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
Set<Integer> set = new TreeSet<>();
for (int i = 0; i < nums.length; i++) {
set.add(nums[i]);
}
int[] arrays = new int[nums.length];
int k = 0;
for (Integer i : set) {
arrays[k++] = i;
}
int max = 0;
int result = 0;
for (int i = 0; i < arrays.length - 1; i++) {
if (arrays[i] + 1 == arrays[i + 1]) {
result++;
} else {
if (result + 1 > max) {
max = result + 1;
}
result = 0;
}
}
//假如在i超出范围的时候没有进行操作就是不行的。所以最后有可能还剩一个没有比较的result。
max = Math.max(max, result + 1);
return max;
}