[Hash-medium] 347. Top K high-frequency elements

[Title]
Given a non-empty integer array, return the top k elements with the highest frequency.
[Example 1]
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
[Example 2]
Input: nums = [1], k = 1
Output: [ 1]
[Hint]
You can assume that the given k is always reasonable, and 1 ≤ k ≤ the number of different elements in the array.
The time complexity of your algorithm must be better than O(n log n), where n is the size of the array.
The question data guarantees the unique answer, in other words, the set of the first k high-frequency elements in the array is unique.
You can return the answers in any order.
[Code]
[Python]

class Solution:
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:
        cnt=dict(Counter(nums))
        cnt=sorted(cnt.items(),key=lambda x:-x[1])
        return [cnt[i][0] for i in range(k)]

Guess you like

Origin blog.csdn.net/kz_java/article/details/114757283