leecode题号347:前K个高频元素,python实现

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

示例 1:

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

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/top-k-frequent-elements
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解法一:字典排序

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

解法二:桶排序

class Solution(object):
    def topKFrequent(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: List[int]
        """
        maps = {}
        #生成字典映射
        for i in nums:
            # print('i:%d,maps.get(i,0):%d' %(i, maps.get(i,0)))
            maps[i] = maps.get(i,0) + 1
        max_time = max(maps.values())
        print(maps)
        #根据最大次数生成桶
        TongList = [[] for i in range(max_time+1)]
        for key ,value in maps.items():
            TongList[value].append(key)
            print(TongList)
        res = []
        for i in range(max_time, 0, -1):
            print('i:%d' %(i))
            if TongList[i]:
                res.extend(TongList[i])
            if len(res) >= k:
                return res[:k]
        
    
        

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

haimianjie2012

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值