一、简述
使用数据结构堆,实现查找数组中的第K大元素。流程如下:数组内容堆化(因为是查找第K大,所以使用大根堆)、依次取出并删除堆的根节点、将剩余元素堆化、取到第K个即为目标元素。
二、代码实现
#include <iostream>
#include <vector>
using namespace std;
int findKth(vector<int> a, int n, int K) {
int heapSize = n;
vector<int> aa(a);
aa.insert(aa.begin(),0);
/*for将数组元素初始化为大根堆*/
for(int root = heapSize / 2; root >= 1; root--){
int rootElement = aa[root];
int child = root * 2;
while(child <= heapSize){
if((child < heapSize) && (aa[child] < aa[child + 1])){
child++;
}
if(rootElement >= aa[child]){
break;
}
else{
aa[child / 2] = aa[child];
child *= 2;
}
}
aa[child / 2] = rootElement;
}
int result = 0;
for(int i = 0; i < K; i++){
result = aa[1]; //取出根节点元素
/*while将剩余元素堆化*/
int lastElement = aa[heapSize --];
int curNode = 1, childNode = 2;
while(childNode <= heapSize){
if((childNode < heapSize) && (aa[childNode] < aa[childNode + 1])){
childNode ++;
}
if(lastElement >= aa[childNode]){
break;
}
else{
aa[childNode / 2] = aa[childNode];
curNode = childNode;
childNode *= 2;
}
}
aa[curNode] = lastElement;
}
return result;
}
int main()
{
vector<int> primes {352, 564,453,2,1,34,5,6,7,8,7,5,67,76,56,45,25,2,2,5,4};
int result = findKth(primes, (int)primes.size(), 8);
cout << "result = " << result << endl;
return 0;
}
三、运行结果
result = 34