파비의 매일매일 공부기록

2023.05.22 Today's Challenge 본문

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)
반응형

'Problem Solving > LeetCode' 카테고리의 다른 글

2023.05.24 Today's Challenge  (0) 2023.05.24
2023.05.23 Today's Challenge  (0) 2023.05.23
2023.05.21 Today's Challenge  (1) 2023.05.21
2023.05.20 Today's Challenge  (0) 2023.05.20
2023.05.19 Today's Challenge  (0) 2023.05.19
Comments