arcbjorn

thoughtbook

RSS Feed

Saturday, February 18, 2023

Top k frequent elements

Leetcode 347 problem.

A function, given an integer array nums and an integer k, to return the k most frequent elements.

Go

  • Time complexity: O(nlog(n))O(n*log(n)) - n is a quantity of numbers
  • Auxiliary space: O(n)O(n) - n is a quantity of all numbers
func topKFrequent(nums []int, k int) []int {
    numberFrequencyMap := make(map[int]int, k)

    // map with a number is a key and value is a frequency of this number in array
    for _, num := range nums {
        numberFrequencyMap[num]++
    }

    var numbers []int
    
    // create numbers' slice with no duplicates
    for num, _ := range numberFrequencyMap {
        numbers = append(numbers, num)
    }
    
    // sort numbers by its frequency values in numberFrequencyMap
    sort.Slice(numbers, func (i int, j int) bool {
        return numberFrequencyMap[numbers[i]] > numberFrequencyMap[numbers[j]]
    })
    
    // return slice with the size up to k elements
    return numbers[:k]
}
Creative Commons Licence