cpp-algo-cases/chapter_heap/top_k.cpp

39 lines
948 B
C++
Raw Normal View History

2024-02-20 16:13:23 +08:00
/**
* File: top_k.cpp
* Created Time: 2023-06-12
* Author: krahets (krahets@163.com)
*/
#include "../utils/common.hpp"
/* <20><><EFBFBD>ڶѲ<DAB6><D1B2><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> k <20><>Ԫ<EFBFBD><D4AA> */
priority_queue<int, vector<int>, greater<int>> topKHeap(vector<int> &nums, int k) {
// <20><>ʼ<EFBFBD><CABC>С<EFBFBD><D0A1><EFBFBD><EFBFBD>
priority_queue<int, vector<int>, greater<int>> heap;
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ǰ k <20><>Ԫ<EFBFBD><D4AA><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
for (int i = 0; i < k; i++) {
heap.push(nums[i]);
}
// <20>ӵ<EFBFBD> k+1 <20><>Ԫ<EFBFBD>ؿ<EFBFBD>ʼ<EFBFBD><CABC><EFBFBD><EFBFBD><EFBFBD>ֶѵij<D1B5><C4B3><EFBFBD>Ϊ k
for (int i = k; i < nums.size(); i++) {
// <20><><EFBFBD><EFBFBD>ǰԪ<C7B0>ش<EFBFBD><D8B4>ڶѶ<DAB6>Ԫ<EFBFBD>أ<EFBFBD><D8A3>򽫶Ѷ<F2BDABB6>Ԫ<EFBFBD>س<EFBFBD><D8B3>ѡ<EFBFBD><D1A1><EFBFBD>ǰԪ<C7B0><D4AA><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
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 << "<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> " << k << " <20><>Ԫ<EFBFBD><D4AA>Ϊ: ";
printHeap(res);
return 0;
}