347. Top K Frequent Elements
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]Input: nums = [1], k = 1
Output: [1]解题要点:
Python:
import heapq
class Solution(object):
def topKFrequent(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
mydict = {}
for n in nums:
if n not in mydict:
mydict[n] = 1
else:
mydict[n] += 1
return heapq.nlargest(k, mydict.keys(), key = mydict.get)Java:
解法二:(桶排序)
Java:
Python:
Last updated