class Solution {
public boolean isPossible(int[] nums) {
Map<Integer, PriorityQueue<Integer>> map = new HashMap<Integer, PriorityQueue<Integer>>();
//建立哈希表;PriorityQueue是基于优先级堆的无界优先级队列
for(int x: nums){//枚举这个参数传进的数组
if(!map.containsKey(x)){
map.put(x,new PriorityQueue<Integer>());
}
if(map.containsKey(x-1)){
int prevLength = map.get(x-1).poll();//poll() 获取并移除此队列的头
//最小堆满足堆顶的元素是最小的,因此堆顶的元素即为最小的子序列长度。
//由于哈希表中的每条记录的值都是最小堆,堆顶元素为最小的子序列长度(以当前的键为最后一个数字的子序列)
//长度短的放在堆顶则get到较短的队列
if(map.get(x-1).isEmpty()){//如果不空则说明前面的划分成多个队列了
map.remove(x-1);//从此队列中移除指定元素的单个实例
//因为已经创建map.(x) 所以移除掉x-1
}
map.get(x).offer(prevLength+1);//将指定元素插入优先级队列
}
else{
map.get(x).offer(1);//出现重复的数字,开一个新队列
}
}
Set<Map.Entry<Integer, PriorityQueue<Integer>>> entrySet = map.entrySet();
//Set<Entry<T,V>> entrySet()方法返回值就是这个map中各个键值对映射关系的集合,可使用它对map进行遍历
for(Map.Entry<Integer, PriorityQueue<Integer>> entry : entrySet) {
PriorityQueue<Integer> queue = entry.getValue();
if(queue.peek()<3){//peek() 获取并移除此队列的头 如果队列为空则返回null
return false;
}
}//检查哈希表中存储的每个子序列的长度是否都不小于 33,即可判断是否可以完成分割
return true;
}
}
659. 分割数组为连续子序列——哈希表+优先级队列的应用
最新推荐文章于 2022-03-15 16:03:23 发布