边工作边刷题:70天一遍leetcode: day 45-1

Top K Frequent Elements

要点:
java:

  • PriorityQueue的definition:Comparator:是一个generic interface,所以new Comparator():加括号表示,同时implement interface 用 {}。内部实现@Override int compare() function
  • 队列操作:offer/poll,map:put/get,set:add/get
  • anonymous class的function是可以直接access外部变量的,比如这题的umap
class Solution(object):
    def topKFrequent(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: List[int]
        """
        from collections import Counter
        from heapq import *
        d = [(cnt, num) for num, cnt in Counter(nums).items()]
        h = []
        for i in xrange(k):
            heappush(h, d[i])
            
        for i in xrange(k, len(d)):
            if h[0][0]<d[i][0]:
                heappop(h)
                heappush(h, d[i])
        
        return [heappop(h)[1] for i in xrange(k)][::-1]

posted @   absolute100  阅读(88)  评论(0编辑  收藏  举报
编辑推荐:
· ASP.NET Core 模型验证消息的本地化新姿势
· 对象命名为何需要避免'-er'和'-or'后缀
· SQL Server如何跟踪自动统计信息更新?
· AI与.NET技术实操系列:使用Catalyst进行自然语言处理
· 分享一个我遇到过的“量子力学”级别的BUG。
阅读排行:
· C# 中比较实用的关键字,基础高频面试题!
· 为什么AI教师难以实现
· 如何让低于1B参数的小型语言模型实现 100% 的准确率
· AI Agent爆火后,MCP协议为什么如此重要!
· 【译】Visual Studio(v17.13)中新的调试和分析特性
点击右上角即可分享
微信分享提示