【Leetcode 347】,前k个高频元素,小根堆的调整

参考题解

题目:给定一个数组,输出 前k个高频元素。
思路:
遍历数组,建立小根堆(小根堆的元素是元组(num,freq),排序规则是每个元素的频率)。
下面使用数组‘heap’,函数’shift_down’,函数‘shift_up’等实现小根堆及其调整(上浮、下沉)。

 def topKFrequent(self, nums: List[int], k: int) -> List[int]:
        def shift_down(arr,root,k):# 下沉的原因是,新换了堆顶,我们需要为这个堆顶元素找到它在堆中的正确位置
        # k表示目前堆的有效大小
            val=arr[root] # root node : <num,freq>
            while root<<1 <k:
                child=root<<1
                if child|1<k and arr[child|1][1]<arr[child][1]:
                    child|=1
                if arr[child][1]<val[1]:
                    arr[root]=arr[child]
                    root=child
                else:
                    break
            arr[root]=val
        def shift_up(arr,child):
        # 上浮调整操作,
        # 上浮原因是,我们在堆的末尾添加了新元素,我们需要为这个新元素找到它在堆中的正确位置
            val=arr[child]
            while child>>1 >0 and arr[child>>1][1]>val[1]:
                arr[child]=arr[child>>1]
                child>>=1
            arr[child]=val

        stat=collections.Counter(nums)# 清点数组nums中的元素个数
        stat=list(stat.items())
        heap=[(0,0)] # 用(0,0)做垫底,为了实现在数组中方便找到父子节点之间的联系,如果父节点的索引是root,那么左孩子的索引是root<<1,右孩子的索引是(root<<1)|1。相反地,如果孩子的索引是child,那么父的索引是child>>1

        for i in range(k):
            heap.append(stat[i])
            shift_up(heap,len(heap)-1)
        for i in range(k,len(stat)):
            if heap[1][1]<stat[i][1]:
                heap[1]=stat[i]
                shift_down(heap,1,k+1)
        return [item[0] for item in heap[1:]]

相关推荐

  1. Leetcode 347】,k高频元素调整

    2024-04-07 04:04:02       138 阅读
  2. Leetcode 347. K 高频元素【中等】

    2024-04-07 04:04:02       37 阅读
  3. Leetcode 347K高频元素

    2024-04-07 04:04:02       24 阅读
  4. LeetCode Hot100 347.k高频元素

    2024-04-07 04:04:02       59 阅读
  5. 【排序算法】LeetCode-347. K 高频元素

    2024-04-07 04:04:02       50 阅读
  6. LeetCode刷题——347. K 高频元素

    2024-04-07 04:04:02       45 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-07 04:04:02       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-07 04:04:02       106 阅读
  3. 在Django里面运行非项目文件

    2024-04-07 04:04:02       87 阅读
  4. Python语言-面向对象

    2024-04-07 04:04:02       96 阅读

热门阅读

  1. OpenAI称其正在研究模仿人类声音的人工智能

    2024-04-07 04:04:02       45 阅读
  2. 》shader命令《--材质函数整理

    2024-04-07 04:04:02       41 阅读
  3. Vue探索之Vue2.x源码分析(一)

    2024-04-07 04:04:02       48 阅读
  4. 创建云原生应用程序:15个要素

    2024-04-07 04:04:02       36 阅读
  5. LeetCode-热题100:347. 前 K 个高频元素

    2024-04-07 04:04:02       39 阅读
  6. 内建函数对象

    2024-04-07 04:04:02       108 阅读
  7. 图像识别与增强现实(AR)的结合

    2024-04-07 04:04:02       42 阅读
  8. docker部署nginx访问宿主机服务,并使用缓存

    2024-04-07 04:04:02       130 阅读
  9. Leetcode 537. 复数乘法

    2024-04-07 04:04:02       132 阅读
  10. Zookeeper 怎么实现分布式锁

    2024-04-07 04:04:02       47 阅读
  11. WebKit简单介绍

    2024-04-07 04:04:02       45 阅读