All Downloads are FREE. Search and download functionalities are using the official Maven repository.

g0601_0700.s0692_top_k_frequent_words.Solution.kt Maven / Gradle / Ivy

There is a newer version: 1.28
Show newest version
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 - 2024 Weber Informatics LLC | Privacy Policy