leetcode347.前 K 个高频元素

1.题目描述

给定一个非空的整数数组,返回其中出现频率前 k 高的元素。

示例 1:

输入: nums = [1,1,1,2,2,3], k = 2
输出: [1,2]
示例 2:

输入: nums = [1], k = 1
输出: [1]
说明:

你可以假设给定的 k 总是合理的,且 1 ≤ k ≤ 数组中不相同的元素的个数。
你的算法的时间复杂度必须优于 O(n log n) , n 是数组的大小。

2.解题思路

1.堆 :O(nlogk)

2.快排:O(n)

3.代码实现

方法一:

下面的代码实leetcode普遍的写法,但是 是错误的,原因:

  • topk (前k大)用小根堆,维护堆大小不超过 k 即可。每次压入堆前和堆顶元素比较,如果比堆顶元素还小,直接扔掉,否则压入堆。检查堆大小是否超过 k,如果超过,弹出堆顶。复杂度是 nlogk
  • 避免使用大根堆,因为你得把所有元素压入堆,复杂度是 nlogn,而且还浪费内存。如果是海量元素,那就挂了。

[注意]

  • 求前 k 大,用小根堆,求前 k 小,用大根堆。面试的时候如果说反了会挂!
class Solution(object):
    def topKFrequent(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: List[int]
        """
        from collections import Counter
        import heapq
        dic = Counter(nums)
        heap = []
        for key,value in dic.items():
            # 最大堆,所以加入负数,python自带的堆是最小堆
            heap.append((-value,key))
        heapq.heapify(heap)
        res = []
        for i in range(k):
            item = heapq.heappop(heap)
            res.append(item[1])
        return res

正确写法:

class Solution(object):
    def topKFrequent(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: List[int]
        """
        from collections import Counter
        import heapq
        dic = Counter(nums)
        heap = []
        for key,value in dic.items():
            if len(heap) == k:
                if value < heap[0][0]:
                    continue
                heapq.heappop(heap)
            heapq.heappush(heap,(value,key))
        res = []
        for i in range(k):
            item = heapq.heappop(heap)
            res.append(item[1])
        return res[::-1]
class Solution:
    def topKFrequent(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: List[int]
        """ 
        count = collections.Counter(nums)   
        return heapq.nlargest(k, count, key=count.get) 

作者:LeetCode
链接:https://leetcode-cn.com/problems/top-k-frequent-elements/solution/qian-k-ge-gao-pin-yuan-su-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

关于heapq.nlargest的用法:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值