leetcode hot 100 前k个高平元素

347. 前 K 个高频元素

已解答

中等

相关标签

相关企业

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

复制代码
class Solution(object):
    def topKFrequent(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: List[int]
        """
        def shift_up(heap , tmp):
            heap.append(tmp)
            child = len(heap)-1
            while child/2>0 and heap[child/2][1]>heap[child][1]:
                # 向上交换一个
                x=heap[child/2]
                heap[child/2] = heap[child]
                heap[child] = x
                child/=2
            



        def shift_down(heap):
            # 把左右子树里面较小的那个放到上面来
            parent =1 
            
            while parent*2  <= k  :
                if parent*2 == k:
                    child = parent*2
                else:
                    if heap[parent*2][1] > heap[parent*2+1][1]:
                        child = parent*2+1
                    else:
                        child = parent*2
                if heap[parent][1]>heap[child][1]:
                    # huan
                    # heap[parent] =heap[child]
                    x = heap[parent]
                    heap[parent] = heap[child]
                    heap[child] = x
                    parent = child
                else:
                    break
           
            
            

        heap=[(None,0)]

        frequency = {}
        frequency_list=[]
        for tmp in nums:
            if frequency.get(tmp)==None:
                frequency[tmp]=1
            else:
                frequency[tmp]+=1
        
        for tmp in frequency.keys():
            frequency_list.append((tmp,frequency[tmp]))


        # print(frequency_list)
        # 对于前k个数字,直接上浮
        for i in range(k):
            shift_up(heap,frequency_list[i])

        
        
        for i in range(k,len(frequency_list)):
            if frequency_list[i][1]>heap[1][1]:
                heap[1] = frequency_list[i]
                shift_down(heap)
                

        ans=[]
        for i in range(1,len(heap)):
            ans.append(heap[i][0])

        return ans

主要是要知道这里需要使用的是堆,而且求最大的几个就是最小堆,因为每次都是把最小的给扔出来,这样才是位置最大的几个。不需要最前面搞个空的东西其实

相关推荐
Rock_yzh9 分钟前
LeetCode算法刷题——54. 螺旋矩阵
数据结构·c++·学习·算法·leetcode·职场和发展·矩阵
ベadvance courageouslyミ15 分钟前
数据结构(一)
数据结构
lightqjx21 分钟前
【C++】对set和map的使用
开发语言·数据结构·c++·stl
AI科技星1 小时前
时空运动的几何约束:张祥前统一场论中圆柱螺旋运动光速不变性的严格数学证明与物理诠释
服务器·数据结构·人工智能·python·科技·算法·生活
别或许2 小时前
哈夫曼编码原理与应用详解
数据结构
集芯微电科技有限公司2 小时前
40V/3A高性能高集成三相BLDC驱动器具有电流及故障诊断功能(FLT)
c语言·数据结构·单片机·嵌入式硬件·fpga开发
liu****2 小时前
13.数据在内存中的存储
c语言·开发语言·数据结构·c++·算法
Unstoppable222 小时前
代码随想录算法训练营第 55 天 | 53. 寻宝(Prim + Kruskal)
数据结构·算法··kruskal·prim
liu****2 小时前
15.自定义类型:联合和枚举
数据结构·c++·剪枝
fantasy5_53 小时前
哈希表实现与解析:从理论到实践
数据结构·散列表