问题描述
给你一个整数数组 nums 和一个整数 k,请你用一个字符串返回其中出现频率前 k 高的元素。请按升序排列。
你所设计算法的时间复杂度必须优于 O(n log n),其中 n 是数组大小。
输入
- nums: 一个正整数数组
- k: 一个整数
返回
返回一个包含 k 个元素的字符串,数字元素之间用逗号分隔。数字元素按升序排列,表示出现频率最高的 k 个元素。
参数限制
- 1 <= nums[i] <= 10^4
- 1 <= nums.length <= 10^5
- k 的取值范围是 [1, 数组中不相同的元素的个数]
- 题目数据保证答案唯一,换句话说,数组中前 k 个高频元素的集合是唯一的
代码
def solution(nums, k):
# Please write your code here
import heapq
from collections import Counter
frequency = Counter(nums)
# 使用小根堆来存储频率最高的 k 个元素
heap = []
for num, freq in frequency.items():
heapq.heappush(heap, (freq, num))
if len(heap) > k:
heapq.heappop(heap)
# 提取堆中的元素并按升序排序
result = [num for freq, num in heap]
result.sort()
return ','.join([str(num) for num in result])
if __name__ == "__main__":
# You can add more test cases here
print(solution( [1,1,1,2,2,3], 2) == "1,2" )
print(solution( [1], 1) == "1" )