[leetcode] 347. Top K Frequent Elements @ python

原题

Given a non-empty array of integers, return the k most frequent elements.

Example 1:

Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
Example 2:

Input: nums = [1], k = 1
Output: [1]
Note:

You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
Your algorithm’s time complexity must be better than O(n log n), where n is the array’s size.

解法1

使用collections.Counter保存每个数字出现的次数, 然后求前k个频率(倒序), 最后遍历字典, 将符合条件的数字放入结果中.
Time: 3*O(n)
Space: O(1)

代码

class Solution:
    def topKFrequent(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: List[int]
        """
        count = collections.Counter(nums)
        res = []
        frequent = sorted(count.values(), reverse = True)[:k]
        for n in count:
            if count[n] in frequent:
                res.append(n)
                
        return res

解法2

利用most_common()方法直接求前k个频率最高的数字, 然后使用list comprehension直接将数字放入列表中.
Time: O(n)
Space: O(1)

代码

class Solution:
    def topKFrequent(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: List[int]
        """
        return [key for key, val in collections.Counter(nums).most_common(k)]
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值