Top k Largest Numbers
题目:
Given an integer array, find the top k largest numbers in it.
分析:
用sort做,复杂度O(nlog(n) ); 用heap做,复杂度O(n + klog(n) );
heap方法确实好,但是当k比较大的时候就会变差了... 这道题目和找第k大有点类似,但是好像用二分法也摆脱不了k这个系数,因为毕竟要做k次,把前k大的都找出来。
解法:
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> maxHeap;
for (int i = 0; i < nums.size(); i++) {
maxHeap.push(nums[i]);
}
vector<int> res;
for (int j = 0; j < k; j ++) {
res.push_back(maxHeap.top() );
maxHeap.pop();
}
return res;
}
};