您的位置:首页 > 产品设计 > UI/UE

347. Top K Frequent Elements【M】【VIP】【字典排序】

2016-05-09 14:58 507 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: