2023-06-12 23:04:01 +08:00
|
|
|
"""
|
|
|
|
File: top_k.py
|
|
|
|
Created Time: 2023-06-10
|
2024-02-07 22:21:18 +08:00
|
|
|
Author: krahets (krahets@163.com)
|
2023-06-12 23:04:01 +08:00
|
|
|
"""
|
|
|
|
|
2023-10-19 16:21:51 +08:00
|
|
|
import sys
|
|
|
|
from pathlib import Path
|
2023-06-12 23:04:01 +08:00
|
|
|
|
2023-10-19 16:21:51 +08:00
|
|
|
sys.path.append(str(Path(__file__).parent.parent))
|
|
|
|
from modules import print_heap
|
2023-06-12 23:04:01 +08:00
|
|
|
|
|
|
|
import heapq
|
|
|
|
|
|
|
|
|
|
|
|
def top_k_heap(nums: list[int], k: int) -> list[int]:
|
|
|
|
"""基于堆查找数组中最大的 k 个元素"""
|
2023-10-26 02:54:19 +08:00
|
|
|
# 初始化小顶堆
|
2023-06-12 23:04:01 +08:00
|
|
|
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)
|
2023-09-02 23:54:38 +08:00
|
|
|
print(f"最大的 {k} 个元素为")
|
2023-06-12 23:04:01 +08:00
|
|
|
print_heap(res)
|