m1ndy5's coding blog

LeetCode 347. Top K Frequent Elements with Python 본문

알고리즘 with python/알고리즘 스터디

LeetCode 347. Top K Frequent Elements with Python

정민됴 2024. 1. 4. 20:06

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

class Solution:
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:
        dic = {}
        answer = []
        for num in nums:
            if num not in dic:
                dic[num] = 1
            else:
                dic[num] += 1
        #[[1, 3번], [2, 2번], ...]
        l = [[key, value] for key, value in dic.items()]
        # 빈도수 기준 정렬(내림차순)
        l.sort(key=lambda x: x[1], reverse = True)

        # k개만 뽑기
        for i in range(k):
            answer.append(l[i][0])

        return answer

그렇게 어려웠던 문제는 아니었던 것 같다!