本文共 704 字,大约阅读时间需要 2 分钟。
Given a non-empty array of integers, return the k most frequent elements.
Example 1:
Input: nums = [1,1,1,2,2,3], k = 2Output: [1,2]
Example 2:
Input: nums = [1], k = 1Output: [1]
首先是统计每个数字出现次数。可以用collections.Counter,也可以自己写方法。
然后将次数做为key,数字做为value。同样的次数可能有多个数字,所以要用list保存。
最后就是按数字的出现次数进行排序。返回前k个即可。
class Solution: def topKFrequent(self, nums: List[int], k: int) -> List[int]: fre={} nfre=collections.defaultdict(list) res=[] for num in nums: fre[num]=fre.get(num, 0)+1 for key,v in fre.items(): nfre[v].append(key) for i in range(len(nums),0,-1): if i in nfre: res.extend(nfre[i]) return res[:k]
转载地址:http://ucrbb.baihongyu.com/