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] <= 104kis 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
numslist.
Let's go through the code step by step:
The
countdictionary is created to store the frequencies of each element in thenumslist.The
freqlist 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
nin thenumslist.Inside the loop, the frequency of each element is calculated and stored in the
countdictionary. Thecount.get(n, 0)retrieves the current frequency of the elementnand 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
countdictionary.Inside this loop, the element
valand its frequencykeyare retrieved.The element
valis appended to thefreqlist at the index corresponding to its frequencykey. This means that elements with the same frequency will be grouped together in thefreqlist.After populating the
freqlist, 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
nin thefreq[i]list, whereirepresents the frequency.Each element
nis appended to theresultlist, which stores the k most frequent elements.After appending an element to the
resultlist, the length of theresultlist is checked. If it equalsk, the desired number of elements has been added, and theresultlist is returned as the final output.If the loop completes without returning the result, it means that there are fewer than
kdistinct elements in the input list, and the function will return theresultlist containing the available distinct elements.

Comments
Post a Comment