Leecode题目指向
- tag:堆
- 215,264,面试题17.09,剑指offer40
堆
简单概念
-
小根堆:子节点总是大于根节点
-
大根堆:子节点总是小于根节点
-
应用场景:堆排序,PriorityQueue
主要操作(以大根堆为例)
“上浮”:
void shiftup(){
while(k>1 && arr[parent(k)]<arr[k]){
//父节点的值小于子节点的值,进行交换
swap(arr,parent(k),k);
k=parent(k)
}
}
“下沉”:
void shiftdown{
while(left(k)<len){
//与左右字节点进行比较
//假设左节点大
int maxInt=left(k);
//与右节点进行比较
if( right(k)<len && arr[maxInt]< arr[right(k)] ) maxInt=right(k);
if( arr[k] > arr[maxInt] ) break;
swap( arr, k , maxInt);
k=maxInt;
}
}
插入(insert):
void insert(int num){
N++;
//把元素加到数组尾部
arr[N]=num;
//对该元素进行"上浮"操作
shiftup(num);
}
删除最大值(delMax):
int delMax(int num){
int max=arr[1];
//把栈顶元素放到末尾
swap(arr,1,N);
arr[N]=null;
N--;
//进行下沉操作
shiftdown(0);
return max;
}
Java中优先队列源码解读(尝试)
官方对PriorityQueue的解释是
An unbounded priority queue based on a priority heap.The elements of the priority queue are ordered according to their{@linkplain Comparable natural ordering}, or by a {@link Comparator}provided at queue construction time, depending on which constructor is used. A priority queue does not permit {@code null} elements.A priority queue relying on natural ordering also does not permit insertion of non-comparable objects (doing so may result i{@code ClassCastException}).
大致的意思就是:
这是一个无界的,基于堆的优先队列;元素的顺序是根据元素的Comparable接口
实现,或者自定义一个比较器该队列是不允许有null
的,同时也不允许无法比较的对象
借此就可以明白在源码中出现的有无比较器的上浮(shuftup)
和下沉(shutdown)
操作
上浮:
下沉:
增加操作:
在提供插入操作的时候,会先判断元素的数量是否大于队列的长度,大于则会进行扩容操作之后进行上浮操作用于维持堆的特性
删除: