题目内容
https://leetcode-cn.com/problems/top-k-frequent-elements/
Given a non-empty array of integers, return the k most 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]
题目思路
这道题目的算法我没有想的很复杂,就是统计+排序。
程序代码
class Solution(object):
def topKFrequent(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
tmp={}
for i in nums:
tmp[i]=tmp.get(i,0)+1
p=sorted(tmp.items(),key=lambda x:x[1],reverse=True)
return [i[0] for i in p[:k]]