Skip to content

Instantly share code, notes, and snippets.

@sviperll
Created April 4, 2019 19:54
Show Gist options
  • Save sviperll/dd6cb2abdc7e67cfa9f46f089542e2c4 to your computer and use it in GitHub Desktop.
Save sviperll/dd6cb2abdc7e67cfa9f46f089542e2c4 to your computer and use it in GitHub Desktop.
Map<String, Integer> map = // ...
int limit = 50;
PriorityQueue<Map.Entry<String, Intger>> queue = new PriorityQueue<>(limit, Comparator.comparing(Map.Entry::getValue).reversed());
for (var entry: map.entrySet()) {
if (queue.size() == limit) {
queue.remove(); // Remove MAXIMAL element
}
queue.add(entry);
}
// After this loop queue contains limit MINIMAL elements
Map<String, Integer> result = new HashMap();
while (!queue.isEmpty()) {
var entry = queue.remove();
result.put(entry.getKey(), entry.getValue());
}
// Total time is O(n * log k) where k is limit,
// considering that limit is small, total time can be seen as O(n)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment