Skip to content

Latest commit

 

History

History
50 lines (32 loc) · 1.4 KB

File metadata and controls

50 lines (32 loc) · 1.4 KB

347. Top K Frequent Elements - 前 K 个高频元素

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

示例 1:

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

示例 2:

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

说明:

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

题目标签:Heap / Hash Table

题目链接:LeetCode / LeetCode中国

题解

Language Runtime Memory
python3 48 ms N/A
class Solution:
    def topKFrequent(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: List[int]
        """
        return [r[0] for r in sorted(list(collections.Counter(nums).items()), key=lambda x: -x[1])[:k]]