题目
给定一个非空的整数数组,返回其中出现频率前 k 高的元素。
输入: nums = [1,1,1,2,2,3], k = 2
输出: [1,2]
思路
哈希表+堆
哈希表保存数组中的每个值以及它的出现频率,Python中用字典实现。
维护一个大小为K的最小堆。
堆中每个节点保存一个键值对,按照(value,key)的方式保存,可以使得堆是按照value值排序。
代码
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
if k < 1: return []
dic = {}
for num in nums:
if num in dic:
dic[num] += 1
else:
dic[num] = 1
h = []
for key,value in dic.items():
if len(h) == k:
if value > h[0][0]:
heapq.heappop(h)
heapq.heappush(h,(value,key))
else:
heapq.heappush(h,(value,key))
del dic
res = []
for i in range(len(h)):
res.append(h[i][1])
del h
return res