347. Top K Frequent Elements

import collections
class Solution(object):
    def topKFrequent(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: List[int]
        """
        return [key for key,_ in collections.Counter(nums).most_common(k)]
import collections
import heapq
class Solution(object):
    def topKFrequent(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: List[int]
        """
        c=collections.Counter(nums)
        
        return heapq.nlargest(k,c,c.get)
        

class Solution(object):
    def topKFrequent(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: List[int]
        """
        counts=dict()
        res = []
        lst = []
        for n in nums:
            counts[n] = counts.get(n,0)+1
        for key, val in counts.items():
            lst.append((val,key))
        lst.sort(reverse=True)
        for i in range(k):
            res.append(lst[i][1])
        return res

你可能感兴趣的:(347. Top K Frequent Elements)