首页 > 其他 > 详细

LeetCode 347. Top K Frequent Elements

时间:2016-06-28 07:02:01      阅读:268      评论:0      收藏:0      [点我收藏+]

 

题目链接:https://leetcode.com/problems/top-k-frequent-elements/

最近一直在练用java写题做比赛,也在学java 8的特性,这题主要是用来练一下java 8的,题目的算法可以写个基于堆的nlog(k),这个没什么好多说的了。

不保证我的java 8程序是最简洁的,我很可能还是写了啰嗦了。

 1 public class Solution {
 2     public List<Integer> topKFrequent(int[] nums, int k) {
 3         Map<Integer, Integer> map = new HashMap<>();
 4         Arrays.stream(nums).forEach(x -> map.merge (x, 1, Integer::sum));
 5         Queue<Integer> queue = new PriorityQueue<>((x, y) -> map.get(x).compareTo(map.get(y)));
 6         map.forEach((key,value) ->{
 7             if (queue.size()<k) {
 8                 queue.add(key);
 9             }
10             else if (map.get(queue.peek())<value){
11                 queue.poll();
12                 queue.add(key);
13             }
14         });
15         List<Integer> list = new ArrayList<>();
16         queue.forEach(list::add);
17         return list;
18     }
19 }

 

 

LeetCode 347. Top K Frequent Elements

原文:http://www.cnblogs.com/micrari/p/5622070.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!