Intermediate Level

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
Input:
nums (int[]) = [1,1,1,2,2,3]
size (int) = 6
k (int) = 2
Return:
(int) 2
Example 2
Input:
nums (int[]) = [1]
size (int) = 1
k (int) = 1
Return:
(int) 1
Example 3
Input:
nums (int[]) = [1,2,2,3,3,3]
size (int) = 6
k (int) = 2
Return:
(int) 2

First 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
Run your code to see the result.