feat: Add the section of Top-K problem (#551)

* Add the section of Top-K problem

* Update my_heap.py

* Update build_heap.md

* Update my_heap.py
This commit is contained in:
Yudong Jin
2023-06-12 23:04:01 +08:00
committed by GitHub
parent 9de5d0bff2
commit a111b94f23
22 changed files with 266 additions and 16 deletions

View File

@ -14,7 +14,7 @@ class MaxHeap:
"""大顶堆"""
def __init__(self, nums: list[int]):
"""构造方法"""
"""构造方法,根据输入列表建堆"""
# 将列表元素原封不动添加进堆
self.max_heap = nums
# 堆化除叶节点以外的其他所有节点

View File

@ -0,0 +1,37 @@
"""
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)