문제
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
'알고리즘' 카테고리의 다른 글
[리트코드(LeetCode)] 1464번 Maximum Product of Two Elements in an Array (1) | 2024.01.07 |
---|---|
[백준(BOJ)] 1920번 수 찾기 (0) | 2024.01.07 |
[리트코드(LeetCode)] 3번 Longest Substring Without Repeating Characters (1) | 2024.01.07 |
[리트코드(LeetCode)] 739번 Daily Temperatures (1) | 2024.01.07 |
[리트코드(LeetCode)] 1337번 The K Weakest Rows in a Matrix (1) | 2024.01.06 |