刷题过程中有时需要用到栈、队列和堆的数据结构,记录一下如何在刷题过程中快速应用

一、栈

1、栈的创建

1
stack = []

2、栈的压入

1
stack.append(x)

3、栈的弹出

1
x = stack.pop()

二、队列

1、队列的创建

1
2
from collections import deque
queue = deque()

2、队列的压入

1
queue.append(x)

3、队列的弹出

1
x = stack.popleft()

三、堆(最小堆)

注意:heapq默认是创建的最小堆,如果需要最大堆,就将-x存入堆中。

1、栈的创建

1
2
3
4
5
import heapq
heap = []#新建
#或者将列表变成小顶堆
nums = [......]
heapq.heapify(nums)

2、堆的压入

1
heapq.heappush(heap,x)

3、堆的弹出

1
heapq.heappop(heaq)

4、寻找序列中最大或最小的N个元素

1
2
3
lista = [64, 92, 93, 83, 85, 50, 10, 49, 28, 60]
print(heapq.nlargest(3, lista)) # [93, 92, 85]
print(heapq.nsmallest(3, lista)) # [10, 28, 49]