Problem description:
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.
Python 求解:
问题需要得到出现次数排名前K的元素,很容易想到hash table来做,元素的值对应着其出现的次数。在python中,字典和hash表类似,现在用python dict来做。
def topKFrequent(self, nums, k):
alist=[]
bdict=dict()
dlist=[]
for i in range(0,len(nums)):
if(nums[i] not in alist):
alist.append(nums[i])
bdict[nums[i]]=1
else:
bdict[nums[i]]+=1
clist = sorted(bdict.iteritems(), key=lambda bdict : bdict[1], reverse=True)
for i in clist:
dlist.append(i[0])
return dlist[0:k]
Python实现LeetCode:找到数组中出现次数最多的k个数
该博客介绍了如何使用Python解决LeetCode中的Top K Frequent Elements问题。通过创建字典来统计数组中元素的频率,然后返回出现次数最多的k个元素。算法的时间复杂度优于O(n log n)。
4567

被折叠的 条评论
为什么被折叠?



