Intermediate Level

Implement the topKFrequentValuesCount method that counts how many values belong to the top k frequent values.

The input contains an integer array nums, its length size, and an integer k. Your task is to count how many distinct values will be selected as the top k most frequent values.

First count the frequency of each distinct value. Then choose up to k values with the highest frequencies and return the number of selected values.

For example, in [1,1,1,2,2,3] with k = 2, the top 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

Use a frequency map to count how many times each value appears.

After counting, the number of possible selected values cannot be more than the number of distinct values and cannot be more than k. If the actual values were needed, we would sort or use a heap by frequency.

Because this method returns only the count, the final result is min(k, number of distinct values).

Pseudocode:

function topKFrequentValuesCount(nums, size, k):
    create empty map frequency
    for each number in nums:
        frequency[number] = frequency[number] + 1
    distinctCount = number of keys in frequency
    if k < distinctCount:
        return k
    return distinctCount
Run your code to see the result.