美文网首页
4 - Medium - 前K个高频元素

4 - Medium - 前K个高频元素

作者: 1f872d1e3817 | 来源:发表于2018-07-05 17:09 被阅读0次

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

例如,

给定数组 [1,1,1,2,2,3] , 和 k = 2,返回 [1,2]。

注意:

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

class Solution:
    def topKFrequent(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: List[int]
        """
        d = {}
        for i in nums:
            if i not in d:
                d[i] = 0
            d[i] += 1
        res = sorted(d.items(),key = lambda x:x[1],reverse = True)
        return [res[i][0] for i in range(k)] 

相关文章

网友评论

      本文标题:4 - Medium - 前K个高频元素

      本文链接:https://www.haomeiwen.com/subject/fegpuftx.html