Skip to content

Instantly share code, notes, and snippets.

@fanzhang312
Created December 6, 2014 00:18
Show Gist options
  • Save fanzhang312/7db44855d8b5b63fc179 to your computer and use it in GitHub Desktop.
Save fanzhang312/7db44855d8b5b63fc179 to your computer and use it in GitHub Desktop.
Find the K largest elements in an unsorted array
public static int[] topK(int[] arr, int k) {
// default is ascending order
Queue<Integer> queue = new PriorityQueue<Integer>();
int i = 0;
for (; i < k; i++) {
queue.add(arr[i]);
}
for (; i < arr.length; i++) {
queue.add(arr[i]);
queue.poll(); // Retrieves and removes the head of this queue, which is smallest element in the queue
}
int[] res = new int[k];
for (int j = 0; j < k; j++) {
res[j] = queue.poll();
}
return res;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment