LeetCode 347. Top K Frequent Elements 时间复杂度(O(nlogk))

时间复杂度(O(nlogk)), 思想:dict_count+堆排序

class Solution:

    def update_top_k(self, top_k: [[int, int]], num_count: (int, int)):

        if top_k[0][1] >= num_count[1]: return
        top_k[0] = num_count
        parent_index, child_index = 0, 1
        top_k_len = len(top_k)
        while child_index < top_k_len:
            if child_index + 1 < top_k_len and top_k[child_index][1] > top_k[child_index + 1][1]:
                child_index += 1
            if top_k[child_index][1] >= top_k[parent_index][1]:
                break
            top_k[child_index], top_k[parent_index] = top_k[parent_index], top_k[child_index]
            parent_index, child_index = child_index, child_index * 2 + 1

    def topKFrequent(self, nums: [int], k: int) -> [int]:
        num_dict = {}
        for num in nums:
            if num not in num_dict:
                num_dict[num] = 1
            else:
                num_dict[num] += 1
        r_count = [[-1, -1] for _ in range(k)]
        for num in num_dict:
            self.update_top_k(r_count, (num, num_dict[num]))
        return [num[0] for num in r_count]

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值