在一个数组中找到前K大的数
样例
给出 [3,10,1000,-99,4,100]
, k = 3
.
返回 [1000, 100, 10]
解题思路:
看到取前X大(小)数,使用优先队列即可。
class Solution {
public:
/**
* @param nums: an integer array
* @param k: An integer
* @return: the top k largest numbers in array
*/
vector<int> topk(vector<int> &nums, int k)
{
// write your code here
priority_queue<int> q;
for(int i : nums)
q.push(i);
vector<int> res;
while(k--)
{
res.push_back(q.top());
q.pop();
}
return res;
}
};