本文主要是介绍347. Top K Frequent Elements【M】【VIP】【字典排序】,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Given a non-empty array of integers, return the k most frequent elements.
For example,
Given [1,1,1,2,2,3]
and k = 2, return [1,2]
.
Note:
- You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
- Your algorithm's time complexity must be better than O(n log n), where n is the array's size.
Subscribe to see which companies asked this question
这个其实挺简单,就是用hash,然后再排序
class Solution(object):def topKFrequent(self, nums, k):dic = {}for i in nums:dic[i] = dic.get(i,0) + 1#print dic.items()l = sorted(dic.iteritems(),key = lambda d:d[1], reverse = True)res = []for i in xrange(k):res += l[i][0],return res
这篇关于347. Top K Frequent Elements【M】【VIP】【字典排序】的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!