Skip to content

Instantly share code, notes, and snippets.

@Sedose
Created April 23, 2023 13:48
Show Gist options
  • Select an option

  • Save Sedose/163203ea4ceaecd6191d126420ee661a to your computer and use it in GitHub Desktop.

Select an option

Save Sedose/163203ea4ceaecd6191d126420ee661a to your computer and use it in GitHub Desktop.
Leetcode. Top K Frequent Elements
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