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

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

相关推荐
houliabc4 分钟前
C语言个人笔记
c语言·数据结构·笔记·算法
_x_w1 小时前
【12】数据结构之基于线性表的排序算法
开发语言·数据结构·笔记·python·算法·链表·排序算法
爱编码的傅同学2 小时前
数据结构(五)——AVL树(平衡二叉搜索树)
数据结构·算法
Bonnie_12152 小时前
02-redis-数据结构实现原理
数据结构·redis·算法
折枝寄北2 小时前
数据结构 | 证明链表环结构是否存在
数据结构·链表
LAOLONG-C2 小时前
先占个日常,等会写。
数据结构
_Vinyoo3 小时前
算法——分治
数据结构·算法
Dovis(誓平步青云)4 小时前
【数据结构】排序算法(下篇·终结)·解析数据难点
c语言·数据结构·学习·算法·排序算法·学习方法·推荐算法
愚润求学6 小时前
【C++】list模拟实现
开发语言·数据结构·c++·list
hxung9 小时前
B+树与红黑树
数据结构·b树