Skip to content

Instantly share code, notes, and snippets.

@orhanobut
Last active December 23, 2015 12:49
Show Gist options
  • Save orhanobut/6637890 to your computer and use it in GitHub Desktop.
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))
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