Implement the topKFrequentElementsCount method that counts how many elements are included in the top k frequent values.
The input array nums contains size integers, and k tells how many high-frequency values should be selected.
Your task is to count how many distinct elements are included when selecting the top k most frequent elements.
This method returns the count of selected elements, not the elements themselves. For example, in [1,1,1,2,2,3] with k = 2, the top two frequent values are 1 and 2, so the answer is 2.
Example 1
[1,1,1,2,2,3]622Example 2
[1]111Example 3
[1,2,2,3,3,3]622First count how many times each number appears.
After building the frequency map, sort or prioritize the distinct numbers by frequency in descending order. Select up to k numbers from this order.
Because the method only returns the count, the final answer is the number of selected distinct values, which is usually min(k, number of distinct values).
Pseudocode:
function topKFrequentElementsCount(nums, size, k):
create empty frequency map
for each value in nums:
frequency[value]++
create list from frequency keys
sort list by frequency in descending order
count = 0
for each value in sorted list:
if count == k:
break
count++
return count