347. Top K Frequent Elements
- Top K Frequent Elements python solution
题目描述
Given a non-empty array of integers, return the k most frequent elements.
解析
和LeetCode 451. Sort Characters By Frequency属于一个问题
// An highlighted block
from collections import Counter
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
most_common = Counter(nums).most_common()
sol = []
for l in range(0,k):
sol.append(most_common[l][0])
return sol
Reference
https://leetcode.com/problems/top-k-frequent-elements/discuss/81697/Python-O(n)-solution-without-sort-without-heap-without-quickselect