Hướng dẫn 692. top k frequent words python - 692. k từ thường xuyên hàng đầu python
Ngày đăng:
07/11/2022
Trả lời:
0
Lượt xem:
6
class Solution: def topKFrequent(self, words, k): """ :type words: List[str] :type k: int :rtype: List[str] """ return [w for w, v in sorted(collections.Counter(words).items(), key = lambda x: (-x[1], x[0])) [:k]] class WordFreq: def __init__(self, freq, word): self.freq = freq self.word = word def __lt__(self, other): if self.freq != other.freq: # return self.freq.__lt__(other.freq) return self.freq < other.freq else: # return self.word.__gt__(other.word) return self.word > other.word class Solution: def topKFrequent(self, words, k): """ :type words: List[str] :type k: int :rtype: List[str] """ counts = collections.Counter(words) topk = [] heapq.heapify(topk) for word, freq in counts.items(): heapq.heappush(topk, WordFreq(freq, word)) # solution 2: # heapq.heappush(topk, (WordFreq(freq, word), word)) if len(topk) > k: heapq.heappop(topk) res = [] for _ in range(k): res.append(heapq.heappop(topk).word) # solution 2: # res.append(heapq.heappop(topk)[1]) return res[::-1]
|