heap

堆是一种数据结构,常用于实现优先队列,解决排序和Top K问题。最大堆中,每个节点的值不大于其父节点,保证根节点为最大元素。二叉堆类似于完全二叉树。接口包括维护堆性质的maxHeapify、构造最大堆的buildMaxHeap以及堆排序算法HeapSort。此外,最大堆还可用于实现查找最大元素和删除最大元素的操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

堆, 优先队列,可以用来排序,计算top k问题

heap property: 

In a max-heap, the max-heap property is that for every node other than the root, A[parent([i)] >= A[i]. That is, the value of the node is at most the value of its parent. Thus the largest element is stored at the root. 

binary heap: like a complete binary tree.

interface:

1. maxHeapify(A, i, n): 维护堆性质。不变量: 执行前 (1) i的left, right subtrees are already max heaps. (2) the value of node i may be smaller than those of its left and right children.  执行后: the tree rooted at node i is max heap.  (n 用来判断left(i), right(i) 是否还是有效的index)  O(lgn)

2. buildMaxHeap: for nodes n/2 to n, are already 1-node heaps. Iterate i from n/2 down to 1, call maxHeapify(A, i, n)  Time complexity: O(n)

HeapSort(A, n): first create a max heap, iterate i from n to 1: swap(A[1], A[i]) (currently A[1] is the largest ele, put it to A[i]), then call maxHeapify(A, 1, i - 1).   O(nlgn)

Use max heap to implement a priority queue.

Maximum(A): return the largest element. O(1)  return A[1].

Extract-Max(A): remove and return the largest element. max = A[1], swap(A[1], A[n]), maxHeapify(A, 1, n-1), return max

IncreaseKey(A, k, x): suppose x >= A[k]. A[k] = x, only need to adjust elements from parent[k] along to 1 (since children of k already satisfy max-heap property). while k > 1:  if(A[parent(k)] < A[k])  swap(A[parent(k)], A[k]); k = parent(k). 

即只需要调整从k到1那条路径上的值即可。

Insert(A, key, n): A.heapSize = A. heapSize + 1; A[n] = Integer.MIN_VALUE; IncreaseKey(A, A.heapSize, key)    O(lgn)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值