题目描述
Given a non-empty array of integers, return the k most frequent elements.
For example,
Given [1,1,1,2,2,3] and k = 2, return [1,2].
1.You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
2.Your algorithm’s time complexity must be better than O(n log n), where n is the array’s size.
先看速度
思路
用Counter()计数,并按value排序,取top k 的key值即可。
class Solution:
def topKFrequent(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
from collections import Counter
counter = Counter(nums)
sorted_counter = sorted(counter.items(),key=lambda x:x[1],reverse=True)
return [i[0] for i in sorted_counter[:k]]