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

 

Top K Frequent Elements - 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


풀이 과정

배열에서 가장 많이 출현한 원소를 k개 반환하는 문제이다.

 

파이썬에서는 collections 모듈의 Counter 클래스를 사용해 리스트에서의 원소의 개수를 쉽게 구할 수 있다.

 

a = [1, 3, 2, 2, 4]

b = collections.Counter(a) = Counter({2: 2, 1: 1, 3: 1, 4: 1})

c = b.most_common() = [(2, 2), (1, 1), (3, 1), (4, 1)]

c = b.most_common(2) = [(2, 2), (1, 1)]

 

위와 같이 활용된다.

 

Counter 클래스를 활용해 문제를 해결하였다.


소스 코드

class Solution:
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:
        ans = collections.Counter(nums).most_common(k)
        answer = []
        for i in (ans):
            answer.append(i[0])
        return answer

+ Recent posts