Here's an implementation that uses counting and sorting:
main.go393 chars18 lines
The function KthMostCommonElement
takes an array of integers arr
and an integer k
, and returns the k
th most common element in the array. We first count the frequency of each element in the array using a map count
, and then convert the map into a slice of pairs (element, frequency)
. We sort this slice by decreasing frequency using sort.Slice
. Finally, we return the number of the k
th element in the sorted slice. Note that if there are ties for the k
th most common element, this implementation will return one of the tied elements arbitrarily.
gistlibby LogSnag