1、题目描述
https://leetcode-cn.com/problems/top-k-frequent-elements/solution/python-dui-pai-xu-by-xxinjiee/
https://leetcode-cn.com/problems/top-k-frequent-elements/solution/python-yi-xing-by-powcai/
给定一个非空的整数数组,返回其中出现频率前 k 高的元素。
示例 1:
输入: nums = [1,1,1,2,2,3], k = 2
输出: [1,2]
示例 2:
输入: nums = [1], k = 1
输出: [1]
说明:
- 你可以假设给定的 k 总是合理的,且 1 ≤ k ≤ 数组中不相同的元素的个数。
- 你的算法的时间复杂度必须优于 O(n log n) , n 是数组的大小。
https://leetcode.com/problems/top-k-frequent-elements/
2、代码详解
class Solution(object):
def topKFrequent(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
from collections import Counter
import heapq
lookup = Counter(nums)
heap = []
for key, val in lookup.items():
heapq.heappush(heap, [-val, key])
res = []
for _ in range(k):
res.append(heapq.heappop(heap)[1])
return res
使用python的常用内建模块collections
使用Counter提取前k个频繁元素,most_common(k)返回一个元组列表。其中元组的第一项是元素,元组的第二项是计数
。内置的zip函数可用于从元组中提取第一个项目。
class Solution(object):
def topKFrequent(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
return zip(*collections.Counter(nums).most_common(k))[0]
其他解法:桶排序