前k个高频单词-数组692-python

python

哈希表+排序

import collections

class Solution:
    def topKFrequent(self, words: List[str], k: int):
        counter = collections.Counter(words)
        res = []

        counter = sorted(counter.items(), key=lambda kv:(-kv[1], kv[0]))
        for i in range(k):
            res.append(counter[i][0])
        
        return res

堆排序

#
# return topK string
# @param strings string字符串一维数组 strings
# @param k int整型 the k
# @return string字符串二维数组
#
import collections
import heapq

class Words:
    def __init__(self, fre, words):
        self.fre = fre
        self.words = words
    
    def __gt__(self, other):
        if self.fre > other.fre or (self.fre==other.fre and self.words < other.words):
            return True
        return False

class Solution:
    
    def topKstrings(self , strings , k ):
        # write code here
        counter = collections.Counter(strings)
        heap = []
        res = []
        for s, count in counter.items():
            heapq.heappush(heap, Words(count, s))
            if len(heap) > k:
                heapq.heappop(heap)
                
        for _ in range(k):
            node = heapq.heappop(heap)
            res.append([node.words, str(node.fre)])
        
        return res[::-1]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值