Leetcode | Top K Frequent Elements (前 K 个高频元素)

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.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值