优先队列/堆

基础

  • 完全二叉树 (complete binary tree)

  • list建堆复杂度为O(n),获得最大值复杂度为O(1),pop取出最大值或插入任意值复杂度为O(log(n)),因为heapify的复杂度为log(n)

    • https://stackoverflow.com/questions/51735692/python-heapify-time-complexity

  • python中只有小顶堆(min heap),最小的元素总是在根结点:heap[0],父节点元素始终小于或等于所有子节点元素

    • 小顶堆pop时,把最小的先弹出去

  • 大顶堆可以通过所有元素变为其负数

  • heap中的item可以是多元素,例如包括其频次,从而记录其状态

  • 求Top K/Median问题时,及时联想到heap

代码

# 创建一个堆,可以使用list来初始化为 [] ,或者通过函数 heapify() ,把一个list转换成堆
import heapq

raw = [3, 1, 5]
heapq.heapify(raw)
print(heapq.heappop(raw))  # python把最小的pop出去
print(heapq.heappushpop(raw, -1))  # 先push 再pop
  • find_Kth_smallest_number

  • 手写heappush

    • Heaps are arrays for which heap[k] <= heap[2k+1] and heap[k] <= heap[2k+2] for all k

Last updated