Create a function that accepts an array of integers nums
and a number k
. The function should find and return the k
elements that appear most frequently in the array.
The problem guarantees that there will be only one valid solution - that is, there won't be any ties when determining the k
most common elements.
The elements can be returned in any sequence you prefer.
Constraints:
nums.length
≤ 10^4nums[i]
≤ 1000k
≤ number of distinct elements in nums
Examples:
// Example 1 const nums1 = [1, 2, 2, 3, 3, 3]; const k1 = 2; console.log(topKFrequent(nums1, k1)); // Output: [2, 3] // Example 2 const nums2 = [7, 7]; const k2 = 1; console.log(topKFrequent(nums2, k2)); // Output: [7]