给定一个非空的整数数组,返回其中出现频率前 k 高的元素。
例如,
给定数组 [1,1,1,2,2,3]
, 和 k = 2,返回 [1,2]
。
注意:
- 你可以假设给定的 k 总是合理的,1 ≤ k ≤ 数组中不相同的元素的个数。
- 你的算法的时间复杂度必须优于 O(n log n) , n 是数组的大小。
class Solution:
def topKFrequent(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
Dict = {}
for i in range(len(nums)):
if nums[i] in Dict:
Dict[nums[i]] = Dict[nums[i]] + 1
else:
Dict[nums[i]] = 1
output = sorted(Dict.items(),key=lambda e:e[1],reverse=True)
#sorted 将字典型字段变为list key为排序标准,支持函数,reverse=True 降序
final = []
for i in range(k):
final.append(output[i][0])
return final