【Leetcode】Top K Frequent Elements Python实现

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]

你可能感兴趣的:(【Leetcode】Top K Frequent Elements Python实现)