python3前 K 个高频元素
给定一个非空的整数数组,返回其中出现频率前 k 高的元素。
示例 1:
输入: nums = [1,1,1,2,2,3], k = 2
输出: [1,2]
示例 2:
输入: nums = [1], k = 1
输出: [1]
提示:
你可以假设给定的 k 总是合理的,且 1 ≤ k ≤ 数组中不相同的元素的个数。
你的算法的时间复杂度必须优于 O(n log n) , n 是数组的大小。
题目数据保证答案唯一,换句话说,数组中前 k 个高频元素的集合是唯一的。
你可以按任意顺序返回答案。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/top-k-frequent-elements
代码实现:
解题思路: 1.将数组中元素读到字典中,并计算每个key的count
2.对字典中的value排序
3.将排序后的key值读取到列表中
4.条件筛选,如果k<= len(list1),返回列表的前k个值
1 class Solution(object): 2 def topKFrequent(self, nums, k): 3 """ 4 :type nums: List[int] 5 :type k: int 6 :rtype: List[int] 7 """ 8 count_dict = dict() 9 for item in nums: 10 if item in count_dict: 11 count_dict[item] += 1 12 else: 13 count_dict[item] = 1 14 count_dict1=sorted(count_dict.items(), key=lambda d: d[1],reverse=True) 15 # sorted(count_dict.values()) 16 list1 = [] 17 18 for j in count_dict1: 19 list1.append(j[0]) 20 while k <= len(list1): 21 return list1[:k] 22