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
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
0347. 前 K 个高频元素
https://algo.itcharge.cn/solutions/0300-0399/top-k-frequent-elements/
Beta Was this translation helpful? Give feedback.
All reactions