数据结构与算法 小顶堆 import heapq nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2] heap = list(nums) heapq.heapify(heap) heap # [-4, 2, 1, 23, 7, 2, 18, 23, 42, 37, 8] print(heapq.nlargest(3, nums)) # Prints [42, 37, 23] print(heapq.nsmallest(3, nums)) # Prints [-4, 1, 2] nlargest() 和 nsmallest() 适合查找元素数量少的情