Created
December 6, 2014 00:18
-
-
Save fanzhang312/7db44855d8b5b63fc179 to your computer and use it in GitHub Desktop.
Find the K largest elements in an unsorted array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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