```python
from typing import (
List,
)
class Solution:
"""
@param nums: the given array
@param k: the given k
@return: the k most frequent elements
we will sort your return value in output
"""
def top_k_frequent(self, nums: List[int], k: int) -> List[int]:
# Write your code here
return [i for i,_ in collections.Counter(nums).most_common(k)]
```
和上面一样对频率排序,自己实现python内置函数
// Some code```python
from typing import (
List,
)
class Solution:
"""
@param nums: the given array
@param k: the given k
@return: the k most frequent elements
we will sort your return value in output
"""
def top_k_frequent(self, nums: List[int], k: int) -> List[int]:
# Write your code here
freq_count = {}
for i in nums:
freq_count[i] = freq_count.get(i,0) + 1
sorted_freq_count = sorted(freq_count.items(), key=lambda x:x[1], reverse=True)
return [i for i,_ in sorted_freq_count[:k]]
```