Description:
Given a non-empty array of integers, return the k most frequent elements.
Example:
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
Input: nums = [1], k = 1
Output: [1]
Ideas:
In NLP, We often meet this problem in data processing, we put all words into a vocabulary to keep
the words and their frequency, and sort the dict with words' frequency, then use it to convert words in
sentence into theid indexes according to vocab.
dict.items() return a list of (key, value) tuple.
Second method is Heapsort.
Code:
class Solution(object):
def topKFrequent(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
nums_dict = {}
for num in nums:
if nums_dict.get(num):
nums_dict[num] += 1
else:
nums_dict[num] = 1
new_ = sorted(nums_dict.items(), key=lambda x: x[1], reverse=True)
k_list = [n for n, _ in new_][:k]
return k_list
Execution time:28 ms
Memory consumption:14.9 MB
# Heapsort
class Solution(object):
def topKFrequent(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
from collections import Counter
import heapq as hq
lookup = Counter(nums)
res = []
heap = []
for num, freq in lookup.items() :
# 如果堆满了(k个元素)
if len(heap) == k :
# 弹出最小频率的元组
if heap[0][0] < freq:
hq.heapreplace(heap, (freq, num))
else :
hq.heappush(heap, (freq, num))
while heap :
res.append(hq.heappop(heap)[1])
return res
作者:yimingen
链接:https://leetcode-cn.com/problems/top-k-frequent-elements/solution/leetcode347onfu-za-du-bu-fen-si-xiang-ji-dui-jie-f/
来源:力扣(LeetCode)
summary
We need to have a good grasp of heapsort , beacuse it often shows up in interviews.