To find the kth most common element in an array, one approach is to use a dictionary to count the occurrence of each element in the array, and then sort the dictionary by value in descending order.
Here's an implementation in Swift:
main.swift330 chars12 lines
This function takes an array of elements of type T
, and an integer k
, and returns the kth most common element in the array, or nil
if there is no such element (i.e., if k
is greater than the number of distinct elements in the array).
The function first defines a dictionary counts
to count the occurrence of each element in the array. The loop iterates over the array, and for each element, increments its count in the dictionary.
The function then sorts the dictionary by value in descending order using the sorted
method, and checks if the kth element exists in the sorted dictionary. If so, it returns the key of that element (i.e., the actual element value). If not, it returns nil
.
gistlibby LogSnag