LeetCode Top K Frequent Elements
来源:互联网 发布:什么是数据库规范化 编辑:程序博客网 时间:2024/06/04 19:23
题意:给出一个数组,求出前k个出现频率最多的数
思路:首先统计每个元素的次数(用Map),然后用堆排序只统计前k个(PriorityQueue)
代码如下:
class Solution{ class Pair implements Comparable<Pair> { int key, value; public int compareTo(Pair b) { return value - b.value; } } public List<Integer> topKFrequent(int[] nums, int k) { Map<Integer, Integer> map = new HashMap<Integer, Integer>(); for (int i = 0; i < nums.length; i++) { if (map.containsKey(nums[i])) { map.put(nums[i], map.get(nums[i]) + 1); } else { map.put(nums[i], 1); } } Comparator<Pair> cmp = new Comparator<Pair>() { public int compare(Pair a, Pair b) { return a.value - b.value; } }; Queue<Pair> queue = new PriorityQueue<Pair>(k, cmp); for(Map.Entry<Integer, Integer> ele: map.entrySet()) { Pair p = new Pair(); p.key = ele.getKey(); p.value = ele.getValue(); if (queue.size() < k) { queue.add(p); } else { if (p.compareTo(queue.peek()) > 0) { queue.poll(); queue.offer(p); } } } List<Integer> res = new ArrayList<Integer>(); while (!queue.isEmpty()) { Pair p = queue.poll(); res.add(p.key); } Collections.sort(res); return res; }}
0 0
- LeetCode|Top K Frequent Elements
- 【Leetcode】Top K Frequent Elements
- LeetCode:Top K Frequent Elements
- [LeetCode] Top K Frequent Elements
- LeetCode:Top K Frequent Elements
- 【leetcode】Top K Frequent Elements
- LeetCode Top K Frequent Elements
- LeetCode:Top K Frequent Elements
- leetcode:Top K Frequent Elements
- LeetCode Top K Frequent Elements
- leetcode Top K Frequent Elements
- LeetCode: Top K Frequent Elements
- LeetCode Top K Frequent Elements
- [LeetCode] Top K Frequent Elements
- LeetCode : Top K Frequent Elements
- Leetcode Top K Frequent Elements
- [leetcode]Top K Frequent Elements
- LeetCode: Top K Frequent Elements
- Android View 深度分析requestLayout、invalidate与postInvalidate
- 华为机试---字符串匹配
- R可视化绘图一ggplot2之qplot
- .NET Framework4.5 & .NET Framework4.0
- 2016.06.04
- LeetCode Top K Frequent Elements
- memcached和redis
- 迭代器的辅助函数实例
- Grabcut算法----opencv2.4.11
- poj 1236 Network of Schools 强连通分量
- 移动端无限滚动加载 js实现原理
- 把centos 7 打造成桌面 系统
- android studio 64位手机+Fresco引起的在arm64位机器上找不到对应的so库
- 第十五周 阅读程序(5)