Last active
December 23, 2015 12:49
-
-
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…
This file contains 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
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