Top K Frequent Elements
Examples
Example 1:
Input: nums = [1,2,2,3,3,3], k = 2
Output: [2,3]
Example 2:
Input: nums = [7,7], k = 1
Output: [7]
Example 1:
Input: nums = [1,2,2,3,3,3], k = 2
Output: [2,3]
Example 2:
Input: nums = [7,7], k = 1
Output: [7]
Given an integer array nums and an integer k, return the k most frequent elements within the array.
The test cases are generated such that the answer is always unique.
You may return the output in any order.
1 <= nums.length <= 10^4.-1000 <= nums[i] <= 10001 <= k <= number of distinct elements in nums.Count the frequency of each number with a hash map, then place numbers into buckets by frequency. The bucket array has indices 0..n, where each bucket i stores the numbers that appear i times. Walk the buckets from high to low, collecting numbers until k elements are gathered.
The frequency map records the exact occurrence count for each distinct number. By grouping numbers into buckets indexed by frequency and iterating from the highest frequency down, we retrieve elements in non-increasing frequency order. Since the answer is unique, the first k elements collected are the correct result.
O(n)O(n)class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
freq = {}
for num in nums:
freq[num] = freq.get(num, 0) + 1
buckets = [[] for _ in range(len(nums) + 1)]
for num, count in freq.items():
buckets[count].append(num)
result = []
for count in range(len(buckets) - 1, 0, -1):
for num in buckets[count]:
result.append(num)
if len(result) == k:
return result
return result