Given a non-empty array of integers, return the k most frequent elements.

输入输出实例:

Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]

本题比较简单,就输出出现的最频繁的k个数字,只需要统计一下每个数字的出现次数,然后按照频率排序,输出前面k个就行了。

class Solution:
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:
        dic = {}
        for i in nums:
            if i in dic:
                dic[i] += 1
            else:
                dic[i] = 1
        dic = sorted(dic.items(), key = lambda x:x[1], reverse=True)
        result = []
        for i in range(k):
            result.append(dic[i][0])
        return result