692. Top K Frequent Words

천승주·2022년 10월 19일
0

Problem

문자열 배열 단어와 정수 k가 주어지면 가장 자주 사용되는 k 문자열을 반환합니다.

가장 높은 빈도에서 가장 낮은 빈도로 정렬된 답변을 반환합니다. 빈도가 같은 단어를 사전순으로 정렬합니다.

Example

Input: words = ["i","love","leetcode","i","love","coding"], k = 2
Output: ["i","love"]
Explanation: "i"와 "love"은 가장 자주 사용되는 두 단어입니다.
알파벳 순서가 낮기 때문에 "i"가 "love" 앞에 옵니다.

Input: 단어 = ["the","day","is","sunny","the","the","the","sunny","is","is"], k = 4
Output: ["the","is","sunny","day"]
Explanation: "the", "is", "sunny", "day"는 4개의 가장 빈번한 단어이며 발생 횟수는 각각 4, 3, 2, 1입니다.

Solution

from collections import Counter

class Solution:
    def topKFrequent(self, words: List[str], k: int) -> List[str]:
        cnt = Counter(words)
        
        print(cnt.items())
        
        most_list = sorted(list(cnt.items()), key=lambda x: [-x[1], x[0]])
        
        print(most_list)
        
        answer = []
        
        for i in range(k):
            answer.append(most_list[i][0])
            
        return answer

0개의 댓글