-
-
Save Sedose/163203ea4ceaecd6191d126420ee661a to your computer and use it in GitHub Desktop.
Leetcode. Top K Frequent Elements
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
| fun topKFrequent(numbers: IntArray, k: Int): IntArray { | |
| val map = numbers.toList().groupingBy { it }.eachCount() | |
| val priorityQueue = PriorityQueue<Pair<Int, Int>>(compareBy { it.second }) | |
| map.forEach { (number, count) -> | |
| priorityQueue.offer(Pair(number, count)) | |
| if (priorityQueue.size > k) { | |
| priorityQueue.poll() | |
| } | |
| } | |
| return IntArray(k) { priorityQueue.poll().first } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment