[一起来刷leetcode吧][18]--No.692 Top K Frequent Words

本文介绍LeetCode上第692题Top K Frequent Words的解决思路及实现代码,采用二叉堆进行堆排序,确保返回的单词按频率从高到低排序,并在频率相同时按字母顺序排列。
Python3.8

Python3.8

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

这篇文章是程序自动发表的,详情可以见 这里
href="http://ounix1xcw.bkt.clouddn.com/github.markdown.css" rel="stylesheet">

这是leetcode的第692题--Top K Frequent Words

  题目 Given a non-empty list of words, return the k most frequent elements.

Your answer should be sorted by frequency from highest to lowest. If two words have the same frequency, then the word with the lower alphabetical order comes first.   思路 用map就很简单。但这道题是考堆排序的,所以我写了个二叉堆来排序。   

show me the code

class Solution:
    def topKFrequent(self, words, k):
        """
        :type words: List[str]
        :type k: int
        :rtype: List[str]
        """
        hp = binaryHeap(sortByFrequency = True,reverse=True)
        for i in words:
            hp.insert(i)
        rst = []
        n = len(hp)
        for i in hp.data:
           print(i.val,i.freq)
        mp = {}
        while hp:
            top = hp.deleteTop()
            if top.freq in mp:
                mp[top.freq].append(top.val)
            else:
                mp[top.freq] = [top.val]
        for i in mp:
            mp[i].sort()
        key = sorted(mp.keys(),reverse = True)
        count = 0
        for i in key:
            for j in mp[i]:
                rst.append(j)
                count =1
                if count == k:return rst

您可能感兴趣的与本文相关的镜像

Python3.8

Python3.8

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值