Python:347. 前K个高频元素( Top K Frequent Elements)

class Solution(object):
    def topKFrequent(self, nums, k):
        d = {}
        res = []
        for i in nums:
            if i in d.keys():
                d[i] += 1
            else:
                d[i] = 1
        d_by_value = sorted(d.items(),key=lambda d: d[1],reverse=True)
        print d_by_value
        for i in xrange(k):
            res.append(d_by_value[i][0])
        return res

重点在于将字典按value排序

你可能感兴趣的:(Python,Leetcode)