nonish5
BAN USERNice one. here's my implementation in java:
---------------------------------------------------------------------
import java.util.PriorityQueue;
public class GetTopK {
public static PriorityQueue<Integer> getTopK(int k, int[] array) {
// Construct an empty queue
PriorityQueue<Integer> minQueue = new PriorityQueue<Integer>();
// Add the first k elements into the queue
for(int i = 0; i < k; i++) {
minQueue.add(new Integer(array[i]));
}
// Go over the rest of the array, and when finding an element larger than the minimum of
// minQueue, remove the minimum and add the new one
for(int i = k; i < array.length; i++) {
Integer minValue = minQueue.peek();
if(array[i] > minValue.intValue()) {
minQueue.poll(); // remove the min from the queue
minQueue.add(new Integer(array[i]));
}
}
// now min queue contains the top k elements.
return minQueue;
}
}
my recursive answer in Java:
- nonish5 May 12, 2013