利用了小顶堆的数据结构特性
#include<iostream>
#include<queue>
#include <functional>
using namespace std;
struct cmp
{
bool operator()(int &a, int &b) const
{
//因为优先出列判定为!cmp,所以反向定义实现最小值优先
return a > b;
}
};
int GetKthElement(int a[], int arrlen, int k)
{
// priority_queue<int, std::vector<int>, greater<int> > m_q;
priority_queue<int, std::vector<int>, cmp> m_q;
for (int i = 0; i < arrlen; i++)
{
if (i<k)
{
m_q.push(a[i]);
}
else
{
if (m_q.top()>a[i])
{
continue;
}
else
{
m_q.pop();
m_q.push(a[i]);
}
}
}
return m_q.top();
}
int main()
{
int a[] = { 1, 8, 7, 11, 19, 16 };
int x = GetKthElement(a, 6, 3);
cout << x << endl;
system("pause");
return 0;
}
结果:
求第三大的元素