LeetCode(No.347)--前K个高频元素

给定一个非空的整数数组,返回其中出现频率前 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 是数组的大小。

思路:传统的就是利用字典来计数,然后取出前K大的值

class Solution:
    def topKFrequent(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: List[int]
        """
        count_list = dict()
        result = list()
        for i in nums:
            count_list[i] = count_list.get(i, 0) + 1
        t = sorted(count_list.items(), key=lambda l : l[1] ,reverse=True)
        for i in range(k):
            result.append(t[i][0])

        return result

但是上述算法复杂度为O(nlogn),并不符合要求,下面是网上看到的牛逼方法

class Solution:
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:
        from collections import Counter
        return [item[0] for item in Counter(nums).most_common(k)] 

猜你喜欢

转载自blog.csdn.net/zuolixiangfisher/article/details/89072525