Given an integer array nums
and an integer k
, return the k
most frequent elements. You may return the answer in any order.
Example 1:
Input: nums = [1,1,1,2,2,3], k = 2 Output: [1,2]
Example 2:
Input: nums = [1], k = 1 Output: [1]
Constraints:
1 <= nums.length <= 105
k
is in the range[1, the number of unique elements in the array]
.- It is guaranteed that the answer is unique.
题目给定一个数组nums和一个整数k,有些数字在数组nums里可能出现多次。要求找出出现频率最高的k个数字。
很明显是一道Top K的题目,可以用优先级队列来搞定,由于要保留频率高的数字排除频率低的数字,可以使用最小堆,heapq默认就是最小堆:用Python刷LeetCode必备知识点1 - 优先级队列。首先遍历一次数组,用一个dict来记录每个数字出现的次数。然后遍历dict把数字及其频率作为一个元组tuple(频率在前数字在后)放入优先级队列,一旦队列中个数超过k就弹出一个,由于是最小堆,被弹出的肯定是队列里频率最小的数字。最后队列里的k个数字就是出现频率最高的。
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
freq = {}
for num in nums:
if num in freq:
freq[num] += 1
else:
freq[num] = 1
pq = []
for num,cnt in freq.items():
heapq.heappush(pq, (cnt, num))
if len(pq) > k:
heapq.heappop(pq)
return [num for (_, num) in pq]