LeetCode—Python—347. 前K个高频元素

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/IOT_victor/article/details/88383730

1、题目描述

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

示例 1:

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

示例 2:

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

说明:

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

https://leetcode.com/problems/top-k-frequent-elements/

2、代码详解

使用python的常用内建模块collections

使用Counter提取前k个频繁元素,most_common(k)返回一个元组列表。其中元组的第一项是元素,元组的第二项是计数
。内置的zip函数可用于从元组中提取第一个项目。

class Solution(object):
    def topKFrequent(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: List[int]
        """
        return zip(*collections.Counter(nums).most_common(k))[0]

其他解法:桶排序

猜你喜欢

转载自blog.csdn.net/IOT_victor/article/details/88383730