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

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

相关推荐
鱼鱼块8 分钟前
二叉搜索树:让数据在有序中生长的智慧之树
javascript·数据结构·面试
jianfeng_zhu1 小时前
二叉树的中序线索化,并通过线索化后遍历二叉树
数据结构·链表
C雨后彩虹1 小时前
5G网络建设
java·数据结构·算法·华为·面试
酸菜牛肉汤面1 小时前
5、索引的数据结构(b+树,hash)
数据结构·b树·哈希算法
爱学习的小仙女!3 小时前
顺序表定义、特点和基本操作(含C代码详细讲解)及时间复杂度
数据结构·算法
TechPioneer_lp4 小时前
27届暑期实习内推:网易美团京东快手等
数据结构·c++·人工智能·笔记·机器学习·面试
月明长歌4 小时前
【码道初阶】Leetcode136:只出现一次的数字:异或一把梭 vs HashMap 计数(两种解法完整复盘)
java·数据结构·算法·leetcode·哈希算法
夏乌_Wx5 小时前
练题100天——DAY34:错误的集合+图片平滑器+最长连续递增序列
数据结构
AuroraWanderll5 小时前
类和对象(四):默认成员函数详解与运算符重载(下)
c语言·数据结构·c++·算法·stl
2401_841495645 小时前
【LeetCode刷题】杨辉三角
数据结构·python·算法·leetcode·杨辉三角·时间复杂度·空间复杂度