![JAR search and dependency download from the Maven repository](/logo.png)
g0601_0700.s0692_top_k_frequent_words.Solution.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-kotlin Show documentation
Show all versions of leetcode-in-kotlin Show documentation
Kotlin-based LeetCode algorithm problem solutions, regularly updated
package g0601_0700.s0692_top_k_frequent_words
// #Medium #String #Hash_Table #Sorting #Heap_Priority_Queue #Counting #Trie #Bucket_Sort
// #Level_1_Day_15_Heap #2023_02_21_Time_239_ms_(81.10%)_Space_37.1_MB_(70.87%)
import java.util.SortedSet
import java.util.TreeSet
@Suppress("NAME_SHADOWING")
class Solution {
fun topKFrequent(words: Array, k: Int): List {
var k = k
val map: MutableMap = HashMap()
for (word in words) {
map[word] = map.getOrDefault(word, 0) + 1
}
val sortedset: SortedSet> = TreeSet(
java.util.Comparator { (key, value): Map.Entry, (key1, value1): Map.Entry ->
return@Comparator if (value != value1) {
value1 - value
} else {
key.compareTo(key1, ignoreCase = true)
}
}
)
sortedset.addAll(map.entries)
val result: MutableList = ArrayList()
val iterator: Iterator> = sortedset.iterator()
while (iterator.hasNext() && k-- > 0) {
result.add(iterator.next().key)
}
return result
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy