Problem Solving/LeetCode

Today's Challenge

fabichoi 2022. 10. 19. 23:45

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

오랫만에 내 손으로 풀어봄.
정렬에 대한 건 살짝 리서치를 하긴 해야했지만 ㅎㅎ;

class Solution:
    def topKFrequent(self, words: List[str], k: int) -> List[str]:
        d = {}
        res = []
        for word in words:
            if not d.get(word):
                d[word] = 1
            else:
                d[word] += 1
        
        sd = sorted(d.items(), key=lambda item: (-item[1], item[0]))
        for i in range(k):
            res.append(sd[i][0])            
        return res
반응형