Skip to content

Instantly share code, notes, and snippets.

@orhanobut
Last active December 23, 2015 12:49
Show Gist options
  • Save orhanobut/6637845 to your computer and use it in GitHub Desktop.
Save orhanobut/6637845 to your computer and use it in GitHub Desktop.
Find the top N of a given integer array. Complexity = O (n.log(k)). I needed to show top 10 data and there was too much data. Brute force wasn't a solution because getting report was slow. I made it as fast as possible. PriorityQueue was a big help because of getting data complexity is O (log(k)). I also made it a general method, thus everyone c…
private static void findTopN(int[] a, int k) {
if (a == null) return;
if (a.length <= k) {
return;
}
PriorityQueue<Integer> pq = new PriorityQueue<Integer> (k);
for (int i = 0; i < a.length; i++) {
pq.add(a[i]);
if (pq.size() > k) {
pq.poll();
}
}
while (!pq.isEmpty()) {
System.out.print(pq.poll() + " ");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment