Given an integer array, find the top k largest numbers in it.
Example
Given [3,10,1000,-99,4,100]
and k = 3
.
Return [1000, 100, 10]
.
求解最大k使用最小堆,求解最小值,使用最大堆;
java
public class Solution {
/*
* @param nums: an integer array
* @param k: An integer
* @return: the top k largest numbers in array
*/
public int[] topk(int[] nums, int k) {
// write your code here
Queue<Integer> queue = new PriorityQueue<>(k);
int val = 0;
for (int i = 0; i < nums.length; i++) {
if (queue.size() < k) {
queue.offer(nums[i]);
} else {
val = queue.peek();
if (val >= nums[i]) {
continue;
} else {
queue.poll();
queue.offer(nums[i]);
}
}
}
int[] arr = new int[k];
for (int i = k - 1; i >= 0; i--) {
arr[i] = queue.poll();
}
return arr;
}
}
python
import heapq
class Solution:
"""
@param: nums: an integer array
@param: k: An integer
@return: the top k largest numbers in array
"""
def topk(self, nums, k):
# write your code here
heapq.heapify(nums)
top = heapq.nlargest(k, nums)
top.sort()
top.reverse()
return top