바위타는 두루미

[leetcode]347. Top K Frequent Elements 본문

Study/Algorithm

[leetcode]347. Top K Frequent Elements

DoRoMii 2019. 8. 10. 12:38
728x90

347. Top K Frequent Elements

 

Given a non-empty array of integers, return the kmost frequent elements.

Example 1:

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

Example 2:

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

 

Note:

  • You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
  • Your algorithm's time complexity must bebetter than O(n log n), where n is the array's size.
class Solution(object):
    def topKFrequent(self, nums, k):
        cnt = {}
        for n in nums:
            cnt[n] = cnt.get(n,0)+1
            
        items = cnt.items()
        items.sort(key=lambda k: k[1], reverse=True)
        return [item[0] for item in items[:k]]
            

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

'Study > Algorithm' 카테고리의 다른 글

[leetcode]162. Find Peak Element  (0) 2019.08.10
[leetcode]347. Top K Frequent Elements  (0) 2019.08.10
[leetcode]75. Sort Colors  (0) 2019.08.10
[leetcode]79. Word Search  (0) 2019.08.10
[leetcode]78. Subsets  (0) 2019.08.10
Comments