题解 | #寻找第K大#
寻找第K大
https://www.nowcoder.com/practice/e016ad9b7f0b45048c58a9f27ba618bf
import heapq # # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param a int整型一维数组 # @param n int整型 # @param K int整型 # @return int整型 # class Solution: def findKth(self , a: List[int], n: int, K: int) -> int: min_heap = [] for num in a: if len(min_heap) < K: heapq.heappush(min_heap, num) else: heapq.heappushpop(min_heap, num) return min_heap[0]
建立了一个堆,先向其中添加K个元素,之后则每次pushpop进新的元素。
补充知识
- heapq.heappush(heap, item)。将 item 的值加入 heap 中,保持堆的不变性。
- heapq.heappop(heap)。弹出并返回 heap 的最小的元素,保持堆的不变性。如果堆为空,抛出 IndexError 。
- heapq.heappushpop(heap, item)。将 item 放入堆中,然后弹出并返回 heap 的最小元素。该组合操作比先调用 heappush() 再调用 heappop() 运行起来更有效率。
- heapq.heapify(x)。将list x 转换成堆,原地,线性时间内。
- heapq.heapreplace(heap, item)。弹出并返回 heap 中最小的一项,同时推入新的 item。 堆的大小不变。 如果堆为空则引发 IndexError。
- heapq.merge(*iterables, key=None, reverse=False)。将多个已排序的输入合并为一个已排序的输出。
- heapq.nlargest(n, iterable, key=None)。从 iterable 所定义的数据集中返回前 n 个最大元素组成的列表。
- heapq.nsmallest(n, iterable, key=None)。从 iterable 所定义的数据集中返回前 n 个最小元素组成的列表。
- 使用 heap[0] ,可以只访问最小的元素而不弹出它。