复杂数据结构
堆
- 堆是一个二叉树,其中每个父节点的值都小于等于其所有子节点的值。
- 数组heap[k]<=heap[2*k+1]
- 列表heap[k]<=heap[2*k+2]
- 整个堆中最小的元素总是位于二叉树的根节点
- Python中提供了heap模块提供相应的支持
import heapq
import random
data = list(range(10))
random.shuffle(data)
data
heap = []
for n in data:
heapq.heappush(heap,n)
heap
[0, 1, 2, 4, 6, 7, 3, 9, 5, 8]
heapq.heappush(heap,0.5)
heap
[0, 0.5, 2, 4, 1, 7, 3, 9, 5, 8, 6]
heapq.heappop(heap)
heap
[0.5, 1, 2, 4, 6, 7, 3, 9, 5, 8]
myheap = [1,2,3,4,5,7,9,0,10,333]
heapq.heapify(mylist)
myheap
[1, 2, 3, 4, 5, 7, 9, 0, 10, 333]
heapq.heapreplace(myheap,333)
myheap
[3, 4, 7, 0, 5, 333, 9, 1, 10, 333]
max_value = (a,b,c) =heapq.nlargest(3,myheap)
max_value
[333, 333, 10]
min_value = (a,b) = heapq.nsmallest(2,myheap)
min_value
[0, 1]
队列
- 队列的特点:FIFO(先进先出) LILO(后进后出)
- 应用场景:
- Python提供了queue模块和collections.deque模块支持队列的操作
import queue
q = queue.Queue()
q.put(0)
q.put(1)
q.put(2)
q.queue
<queue.Queue at 0x23a656ea688>
q.get()
0
q.queue
deque([1, 2])
q.get()
1
q.queue
deque([2])
后进先出队列
import queu