mirror of
https://github.com/krahets/hello-algo.git
synced 2024-12-27 02:26:29 +08:00
a005c6ebd3
* Update avatar's link in the landing page * Bug fixes * Move assets folder from overrides to docs * Reduce figures' corner radius * Update copyright * Update header image * Krahets -> krahets * Update the landing page
39 lines
949 B
Python
39 lines
949 B
Python
"""
|
|
File: top_k.py
|
|
Created Time: 2023-06-10
|
|
Author: krahets (krahets@163.com)
|
|
"""
|
|
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
sys.path.append(str(Path(__file__).parent.parent))
|
|
from modules import print_heap
|
|
|
|
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)
|