LeetCode - Top K Frequent Elements(347)

marafo·2021년 6월 9일

Hash Table - Medium

from collections import Counter

class Solution:
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:
        dic = list(collections.Counter(nums).items())
        answer = []
        c = 0
        
        dic = sorted(dic, key = lambda x: x[1], reverse = True)
        
        for i in range(len(dic)):
            if c == k:
                break
            
            answer.append(dic[i][0])
            c += 1
                
        return answer
        
profile
프론트 개발자 준비

0개의 댓글