Top k Largest Numbers II
ID: 545; medium
Solution 1 (Java)
public class Solution {
private Queue<Integer> minheap;
private int capacity;
/*
* @param k: An integer
*/
public Solution(int k) {
minheap = new PriorityQueue<>();
capacity = k;
}
/*
* @param num: Number to be added
* @return: nothing
*/
public void add(int num) {
if (minheap.size() < capacity) {
minheap.offer(num);
return;
}
if (num > minheap.peek()) {
minheap.poll();
minheap.offer(num);
}
}
/*
* @return: Top k element
*/
public List<Integer> topk() {
// convert heap to list by initialization
List<Integer> res = new ArrayList<>(minheap);
Collections.sort(res, Collections.reverseOrder());
return res;
// // Use iterator
// List<Integer> res = new ArrayList<>();
// Iterator it = minheap.iterator();
// while (it.hasNext()) {
// res.add((Integer)it.next());
// }
// Collections.sort(res, Collections.reverseOrder());
// return res;
}
}Notes
It is important to notice here that we used a min heap. Otherwise, we do not know when to offer or poll based on the number and also the size of the heap.
Do not forget to reverse the order since the problem is asking for the top k largest numbers.
Solution 2 (Java)
Notes
This is a version of the solution if we do not use a built-in priority queue.
This solution utilizes the sift up and sift down methods used in Heapify.
Last updated
Was this helpful?