소프트웨어에 대한 모든 것

LeetCode 풀기 - 692. Top K Frequent Words 본문

알고리즘/LeetCode

LeetCode 풀기 - 692. Top K Frequent Words

앤테바 2022. 2. 23. 18:30
반응형

692. Top K Frequent Words

https://leetcode.com/problems/top-k-frequent-words/

 

Top K Frequent Words - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

문제)

솔루션1) sorted() 다중 정렬

sorted() 함수의 다중 정렬을 사용하면 문제를 쉽게 해결할 수 있습니다.

class Solution(object):
    def topKFrequent(self, words, k):
        """
        :type words: List[str]
        :type k: int
        :rtype: List[str]
        """                
        counter = Counter(words)
        words = list(counter.items())
        
        # counter 내림차순 정렬, word 오른차순 정렬
        words = sorted(words, key=lambda x: (-x[1], x[0]))
        
        words = words[:k]
        return [word[0] for word in words]

솔루션2) PriorityQueue 사용

우선순위큐를 사용합니다.

Word라는 클래스를 구현하고 우선순위 큐에서 Word간 비교를 하기 위해서  __lt__() 함수를 정의합니다.

from queue import PriorityQueue

class Word:
    def __init__(self, word, count):
        self.word = word
        self.count = count

    # count 내림차순, word 오름차순
    def __lt__(self, other):
        if self.count > other.count:
            return True
        elif self.count == other.count:
            if self.word < other.word:
                return True
        return False

class Solution(object):
    def topKFrequent(self, words, k):
        counter = Counter(words)

        words = []
        for w, c in counter.items():
            words.append(Word(w, c))

        q = PriorityQueue()
        for word in words:
            q.put(word)
            
        return [q.get().word for i in range(k)]

 

함께 보면 좋은 글:

2022.02.24 - [파이썬] - [파이썬] 우선순위큐(PriorityQueue) 사용법

2022.02.24 - [파이썬] - [파이썬] sorted() 정렬 함수 파헤치기

반응형
Comments