mirror of
https://github.com/krahets/hello-algo.git
synced 2024-12-26 00:26:29 +08:00
a111b94f23
* Add the section of Top-K problem * Update my_heap.py * Update build_heap.md * Update my_heap.py
37 lines
923 B
Python
37 lines
923 B
Python
"""
|
|
File: top_k.py
|
|
Created Time: 2023-06-10
|
|
Author: Krahets (krahets@163.com)
|
|
"""
|
|
|
|
import sys, os.path as osp
|
|
|
|
sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__))))
|
|
from modules import *
|
|
|
|
import heapq
|
|
|
|
|
|
def top_k_heap(nums: list[int], k: int) -> list[int]:
|
|
"""基于堆查找数组中最大的 k 个元素"""
|
|
heap = []
|
|
# 将数组的前 k 个元素入堆
|
|
for i in range(k):
|
|
heapq.heappush(heap, nums[i])
|
|
# 从第 k+1 个元素开始,保持堆的长度为 k
|
|
for i in range(k, len(nums)):
|
|
# 若当前元素大于堆顶元素,则将堆顶元素出堆、当前元素入堆
|
|
if nums[i] > heap[0]:
|
|
heapq.heappop(heap)
|
|
heapq.heappush(heap, nums[i])
|
|
return heap
|
|
|
|
|
|
"""Driver Code"""
|
|
if __name__ == "__main__":
|
|
nums = [1, 7, 6, 3, 2]
|
|
k = 3
|
|
|
|
res = top_k_heap(nums, k)
|
|
print(f"最大的 {k} 个元素为")
|
|
print_heap(res)
|