LeetCode 347-前 K 个高频元素

'''
给你一个整数数组 nums 和一个整数 k ,请你返回其中出现频率前 k 高的元素。你可以按 任意顺序 返回答案。



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

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

提示:
1 <= nums.length <= 105
k 的取值范围是 [1, 数组中不相同的元素的个数]
题目数据保证答案唯一,换句话说,数组中前 k 个高频元素的集合是唯一的

进阶:你所设计算法的时间复杂度 必须 优于 O(n log n) ,其中 n是数组大小。

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

from collections import Counter
import collections
def topKFrequent(nums, k):
    global cur
    hashmap = {}
    for key in nums:
        if key not in hashmap:
            hashmap[key] = 1
        else:
            hashmap[key] += 1

    res = []
    while k > 0:
        tmp = 0
        for num in hashmap:
            if hashmap[num] > tmp:
                tmp = hashmap[num]
                cur = num
        hashmap[cur] = -1
        res.append(cur)
        k -= 1
    return res

###Counter most_common()方法
list1 = [1,9,9,5,0,8,0,9]
temp = Counter(list1)
print(temp.most_common(0))
print(temp.most_common(1))
print(temp.most_common(2))
print(temp.most_common(3))
print([item[0] for item in temp.most_common(2)])

def topKFrequent1(nums, k):
    count = collections.Counter(nums)
    return [item[0] for item in count.most_common(k)]

def topKFrequent2(nums, k):
    res = [item[0] for item in sorted(Counter(nums).items(), key= lambda x: x[1], reverse=True)[:k]]
    return res

if __name__ == '__main__':
    print(topKFrequent([1,1,1,2,2,3], 2))
    print(topKFrequent1([2,2,1,1,1,3], 2))
    print(topKFrequent2([2,2,1,1,1,3], 2))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值