0347. 前 K 个高频元素 #118
Replies: 2 comments 1 reply
-
用heapq模块的解法 import heapq
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
# 优先队列
nums_dict = dict()
for num in nums:
if num not in nums_dict:
nums_dict[num] = 1
else:
nums_dict[num] += 1
# 降重
nums_list = list(set(nums))
# or nums_dict.keys()
q = []
for i in range(len(nums_list)):
heapq.heappush(q, (nums_dict[nums_list[i]], nums_list[i]))
return [item[1] for item in heapq.nlargest(k, q)][:k] |
Beta Was this translation helpful? Give feedback.
1 reply
-
可以先计算频次,然后再计算前k个高频的数 |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
0347. 前 K 个高频元素
标签:数组、哈希表、分治、桶排序、计数、快速选择、排序、堆(优先队列); 难度:中等; 题目链接 0347. 前 K 个高频元素 - 力扣 (https://leetcode.cn/problems/top-k-frequent-elements/); 题目大意 描述:给定一个整数数组$nums$ 和一个整数 $k$ 。 要求:返回出现频率前 $k$ ...
https://algo.itcharge.cn/Solutions/0300-0399/top-k-frequent-elements/
Beta Was this translation helpful? Give feedback.
All reactions