对这一题,最直截了当的想法就是,先将数组排序好,然后根绝 a[i - 1] + 1 == a[i] 的关系判断最长的连续序列
class Solution {
public int longestConsecutive(int[] nums) {
int max = 0, index = 1, length = nums.length;
if (length == 0) return 0;
// 这里使用优先队列进行排序
PriorityQueue<Integer> pq = new PriorityQueue<>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1 - o2;
}
});
// 通过set去重
HashSet<Integer> set = new HashSet<>();
for (int i = 0; i < length; i++) {
if (!set.contains(nums[i])) {
set.add(nums[i]);
pq.offer(nums[i]);
}
}
int anchor = pq.poll();
while (!pq.isEmpty()) {
int num = pq.poll();
if (anchor + 1 == num) {
index++;
} else {
max = Math.max(max, index);
index = 1;
}
anchor = num;
}
max = Math.max(max, index);
return max;
}
}
然而,在本题中,要求时间复杂度为0(n)级别,所以必须要想一个办法,只要遍历一次数组,就可以得出答案,这里我们想到,上面的代码中使用了set,既然有set,完全可以借助set来实现a[i - 1] + 1 == a[i]的比较。这里使用TreeSet,同时完成去重和排序的任务
class Solution {
public int longestConsecutive(int[] nums) {
int max = 0, index = 1, length = nums.length;
if (length == 0) return 0;
TreeSet<Integer> set = new TreeSet<>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1 - o2;
}
});
for (int i = 0; i < length; i++) {
set.add(nums[i]);
}
Iterator<Integer> iterator = set.iterator();
// 获得第一个值
int anchor = iterator.next();
while (iterator.hasNext()) {
int num = iterator.next();
if (anchor + 1 == num) {
index++;
} else {
max = Math.max(max, index);
index = 1;
}
anchor = num;
}
max = Math.max(max, index);
return max;
}
}
通过上面的方式,远远降低了内存消耗