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

@@ -61,5 +61,6 @@ int main() {
priority_queue<int, vector<int>, greater<int>> minHeap(input.begin(), input.end());
cout << "输入列表并建立小顶堆后" << endl;
printHeap(minHeap);
return 0;
}
}

View File

@@ -151,4 +151,6 @@ int main() {
/* 判断堆是否为空 */
bool isEmpty = maxHeap.empty();
cout << "\n堆是否为空 " << isEmpty << endl;
return 0;
}

View File

@@ -0,0 +1,37 @@
/**
* File: top_k.cpp
* Created Time: 2023-06-12
* Author: Krahets (krahets@163.com)
*/
#include "../utils/common.hpp"
/* 基于堆查找数组中最大的 k 个元素 */
priority_queue<int, vector<int>, greater<int>> topKHeap(vector<int> &nums, int k) {
priority_queue<int, vector<int>, greater<int>> heap;
// 将数组的前 k 个元素入堆
for (int i = 0; i < k; i++) {
heap.push(nums[i]);
}
// 从第 k+1 个元素开始,保持堆的长度为 k
for (int i = k; i < nums.size(); i++) {
// 若当前元素大于堆顶元素,则将堆顶元素出堆、当前元素入堆
if (nums[i] > heap.top()) {
heap.pop();
heap.push(nums[i]);
}
}
return heap;
}
// Driver Code
int main() {
vector<int> nums = {1, 7, 6, 3, 2};
int k = 3;
priority_queue<int, vector<int>, greater<int>> res = topKHeap(nums, k);
cout << "最大的 " << k << " 个元素为: ";
printHeap(res);
return 0;
}

View File

@@ -13,16 +13,6 @@
#include <sstream>
#include <string>
/* Expose the underlying storage of the priority_queue container */
template <typename T, typename S, typename C> S &Container(priority_queue<T, S, C> &pq) {
struct HackedQueue : private priority_queue<T, S, C> {
static S &Container(priority_queue<T, S, C> &pq) {
return pq.*&HackedQueue::c;
}
};
return HackedQueue::Container(pq);
}
/* Find an element in a vector */
template <typename T> int vecFind(const vector<T> &vec, T ele) {
int j = INT_MAX;
@@ -217,6 +207,16 @@ template <typename TKey, typename TValue> void printHashMap(unordered_map<TKey,
}
}
/* Expose the underlying storage of the priority_queue container */
template <typename T, typename S, typename C> S &Container(priority_queue<T, S, C> &pq) {
struct HackedQueue : private priority_queue<T, S, C> {
static S &Container(priority_queue<T, S, C> &pq) {
return pq.*&HackedQueue::c;
}
};
return HackedQueue::Container(pq);
}
/* Print a Heap (PriorityQueue) */
template <typename T, typename S, typename C> void printHeap(priority_queue<T, S, C> &heap) {
vector<T> vec = Container(heap);

View File

@@ -0,0 +1,39 @@
/**
* File: top_k.java
* Created Time: 2023-06-12
* Author: Krahets (krahets@163.com)
*/
package chapter_heap;
import utils.*;
import java.util.*;
public class top_k {
/* 基于堆查找数组中最大的 k 个元素 */
static Queue<Integer> topKHeap(int[] nums, int k) {
Queue<Integer> heap = new PriorityQueue<Integer>();
// 将数组的前 k 个元素入堆
for (int i = 0; i < k; i++) {
heap.add(nums[i]);
}
// 从第 k+1 个元素开始,保持堆的长度为 k
for (int i = k; i < nums.length; i++) {
// 若当前元素大于堆顶元素,则将堆顶元素出堆、当前元素入堆
if (nums[i] > heap.peek()) {
heap.poll();
heap.add(nums[i]);
}
}
return heap;
}
public static void main(String[] args) {
int[] nums = { 1, 7, 6, 3, 2 };
int k = 3;
Queue<Integer> res = topKHeap(nums, k);
System.out.println("最大的 " + k + " 个元素为");
PrintUtil.printHeap(res);
}
}

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)