알고리즘

[리트코드(LeetCode)] 347번 Top K Frequent Elements

욘아리 2024. 1. 7. 18:14

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

 

Top K Frequent Elements - LeetCode

Can you solve this real interview question? Top K Frequent Elements - Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.   Example 1: Input: nums = [1,1,1,2,2,3], k = 2 Output: [1,2]

leetcode.com

상위 k번 이상 등장하는 요소를 구하는 문제다.

예시

Example 1:

Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]

 

Example 2:

Input: nums = [1], k = 1
Output: [1]

풀이

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

    	return res

 

- Counter에 있는 빈도 수가 높은 순서대로 아이템을 추출하는 most_common()을 사용한다.

 

참조 : 박상길, 파이썬 알고리즘 인터뷰  https://github.com/onlybooks/algorithm-interview