Last active
December 23, 2015 12:49
-
-
Save orhanobut/6637890 to your computer and use it in GitHub Desktop.
Find the top K of a given integer array.
Complexity = O(n.log(k))
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
public static void findTopK(int[] a, int k){ | |
PriorityQueue<Integer> pq = new PriorityQueue<Integer>(k+1); | |
for (int i : a){ | |
if (!pq.contains(i)){ | |
pq.add(i); | |
} | |
if (pq.size() > k){ | |
pq.poll(); | |
} | |
} | |
while (!pq.isEmpty()){ | |
System.out.println(pq.poll()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment