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

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

相关推荐
j_xxx404_7 分钟前
蓝桥杯基础--进制转换
开发语言·数据结构·c++·算法·职场和发展·蓝桥杯
丶小鱼丶42 分钟前
数据结构和算法之【堆】
java·数据结构
马猴烧酒.1 小时前
【面试八股|操作系统】操作系统常见面试题详解笔记
java·linux·服务器·网络·数据结构·算法·eclipse
im_AMBER1 小时前
Leetcode 146 爬楼梯 | 打家劫舍
数据结构·算法·leetcode
㓗冽1 小时前
2026.03.25(第一天)
数据结构
cpp_25011 小时前
P1968 [CHCI 2001 Regional Competition Seniors] 美元汇率
数据结构·c++·算法·题解·洛谷·线性dp
博界IT精灵1 小时前
树的概念与性质(哈喜老师)
数据结构
小此方2 小时前
Re:从零开始的 C++ STL篇(八)深度解构AVL树自平衡机制:平衡维护与旋转调整背后的严密逻辑
开发语言·数据结构·c++·算法·stl
2301_789015622 小时前
封装哈希表实现unordered_set/undered_map
c语言·数据结构·c++·算法·哈希算法
独断万古他化2 小时前
【算法通关】递归:汉诺塔、合并链表、反转链表、两两交换、快速幂全解
数据结构·算法·链表·递归