Given an integer array nums
and an integer k, return the k
most frequent elements. You may return the answer in any order.
Example 1:
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
Example 2:
Input: nums = [1], k = 1
Output: [1]
Constraints:
1 <= nums.length <= 105
-104 <= nums[i] <= 104
k
is in the range[1, the number of unique elements in the array]
.- It is guaranteed that the answer is unique.
Follow up: Your algorithm's time complexity must be better than O(n log n)
, where n is the array's size.
SOLUTION:
- Time complexity:
- O(n), where n is the number of elements in the
nums
list.
Let's go through the code step by step:
The
count
dictionary is created to store the frequencies of each element in thenums
list.The
freq
list is initialized as an empty list with a length oflen(nums) + 1
. This list will be used to store the elements grouped by their frequencies.A loop is used to iterate over each element
n
in thenums
list.Inside the loop, the frequency of each element is calculated and stored in the
count
dictionary. Thecount.get(n, 0)
retrieves the current frequency of the elementn
and increments it by 1. If the element is not present in the dictionary, it defaults to 0 and adds 1 to it.Another loop iterates over the key-value pairs in the
count
dictionary.Inside this loop, the element
val
and its frequencykey
are retrieved.The element
val
is appended to thefreq
list at the index corresponding to its frequencykey
. This means that elements with the same frequency will be grouped together in thefreq
list.After populating the
freq
list, another loop is used to iterate over the elements in reverse order, starting from the last index.Inside this loop, another nested loop iterates over the elements
n
in thefreq[i]
list, wherei
represents the frequency.Each element
n
is appended to theresult
list, which stores the k most frequent elements.After appending an element to the
result
list, the length of theresult
list is checked. If it equalsk
, the desired number of elements has been added, and theresult
list is returned as the final output.If the loop completes without returning the result, it means that there are fewer than
k
distinct elements in the input list, and the function will return theresult
list containing the available distinct elements.
Comments
Post a Comment