Created
April 4, 2019 19:54
-
-
Save sviperll/dd6cb2abdc7e67cfa9f46f089542e2c4 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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