用python写leetcode【12】 -- 前K个高频元素(347)
2019-03-18 11:19
330 查看
文章目录
周末生病了,现在还没好。。。。先写点简单的。
前K个高频元素(347)
题目
给定一个非空的整数数组,返回其中出现频率前 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 是数组的大小。
思路
主要是学习了Python标准库——collections模块的Counter类,可以参考这里
代码
class Solution: def topKFrequent(self, nums, k): """ :type nums: List[int] :type k: int :rtype: List[int] """ dic = collections.Counter(nums) res = dic.most_common(k) return [ele[0] for ele in res]
相关文章推荐
- LeetCode--347. Top K Frequent Elements(前K个高频元素)Python
- LeetCode-Python-347. 前K个高频元素
- 【LeetCode题解】347_前K个高频元素(Top-K-Frequent-Elements)
- leetcode之12.整数转罗马数字python实现
- [LeetCode] 347. Top K Frequent Elements 前K个高频元素
- LeetCode 12 Integer to Roman(C,C++,Java,Python)
- LeetCode 12. 整数转罗马数字 Python
- leetcode(12),Ugly Number(python)
- leetcode 计算二叉树中出现最多的元素,Python实现
- LeetCode 496. 下一个更大元素 I(python)
- leetcode的python实现 刷题笔记27:移除元素
- python写算法题:leetcode: 12. Integer to Roman
- [leetcode: Python]12. Integer to Roman
- leetcode-前K个高频元素
- leetcode 27 移除元素 (python)
- Leetcode做题日记:27. 移除元素(PYTHON)
- leetcode_452. Minimum Number of Arrows to Burst Balloons 用最小的箭击破气球,python列表按元素排序
- LeetCode题解(python)-12. 整数转罗马数字
- Leetcode 27_移除元素 --python
- leetcode-347. 前K个高频元素