leetcode_347. Top K Frequent Elements 找出現頻率最高的前k個元素
題目:
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.
題意:
給定一個數組和常數k,求陣列中出現頻率最高的前k個元素
程式碼:
class Solution(object):
def topKFrequent(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
n = len(nums)
if k >= n :
return nums
else :
dic = {}
res = []
for x in nums :
if x not in dic :
dic[x] = 0
dic[x] += 1
dic = sorted(dic.items(), key=lambda item:item[1], reverse=True) #python的排序真不好記啊,排序後的結果是一個list,每個list元素也是個list,不再是字典的樣子
for i in range(k) :
res.append(dic[i][0]) #dic[i][0]相當於原來字典的鍵
return res
筆記:
可能這個方法並不好