题目描述:
给定一个非空的整数数组,返回其中出现频率前 k 高的元素。
示例 1:
输入: nums = [1,1,1,2,2,3], k = 2
输出: [1,2]
示例 2:
输入: nums = [1], k = 1
输出: [1]
解题思路:
使用Python中的字典存储各元素出现的次数,key为对应元素,value为对应元素出现的次数。再对字典按照值进行降序排序。
Python3代码:
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
dict1 = {}
for i,num in enumerate(nums):
if num in dict1:
dict1[num] = dict1[num]+1
else:
dict1[num] = 1
output = sorted(dict1.items(), key=lambda e:e[1], reverse=True)
final = []
for i in range(k):
final.append(output[i][0])
return final
注:
字典中按“值”排序:可以使用内置的sorted()函数,常用形式:sorted(dict.items(), key=lambda e:e[1], reverse=True), 其中dict.items()返回的是一个列表,列表里的每个元素是一个键和值组成的元组。e表示dict.items()中的一个元素,e[1]表示按值排序,e[0]表示按键排序。
sorted(iterable[, cmp[, key[, reverse]]])
iterable:是可迭代类型类型;
cmp:用于比较的函数,比较什么由key决定,有默认值,迭代集合中的一项;
key:用列表元素的某个属性和函数进行作为关键字,有默认值,迭代集合中的一项;
reverse:排序规则. reverse = True 或者 reverse = False,有默认值,默认为升序排列(False)。