Problem Solving/LeetCode
2023.05.22 Today's Challenge
fabichoi
2023. 5. 22. 23:45
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
heapq의 nlargest 함수를 이용해서 풀면 간단히 풀림.
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
if k == len(nums):
return nums
cnt = Counter(nums)
return heapq.nlargest(k, cnt.keys(), key=cnt.get)
반응형