Skip to content

Commit

Permalink
重新回顾优先队列的写法
Browse files Browse the repository at this point in the history
  • Loading branch information
Xikl committed Jan 6, 2019
1 parent 85d9883 commit 4e84d98
Showing 1 changed file with 16 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import com.ximo.datastructuresinaction.queue.PriorityQueue;

import java.util.*;
import java.util.function.Function;

import static java.util.stream.Collectors.counting;
import static java.util.stream.Collectors.groupingBy;
Expand Down Expand Up @@ -72,23 +73,36 @@ public List<Integer> topKFrequentByMyQueue(int[] nums, int k) {
return result;
}

/** 用java的自带的优先队列实现 */
/**
* 用java的自带的优先队列实现
* 统计频次最大的那个 放入
*
* @param nums 数组
* @param k 前几个
* @return 前k个元素
*/
public List<Integer> topKFrequentByJavaQueue(int[] nums, int k) {
// 将nums按照出现频率变为一个map
Map<Integer, Long> numFrequency =
Arrays.stream(nums).boxed().collect(groupingBy(num -> num, counting()));
Arrays.stream(nums).boxed().collect(groupingBy(Function.identity(), counting()));

// java中采用的是小顶堆的实现
java.util.Queue<Integer> pq = new java.util.PriorityQueue<>((prev , next) -> {
Long compareResult = numFrequency.get(prev) - numFrequency.get(next);
return compareResult.intValue();
});

// 遍历该map
numFrequency.forEach((key, value) -> {
// 小于前k个元素
if (pq.size() < k) {
// 直接添加
pq.add(key);
// 如果当前元素的出现频率大于堆首的元素的出现频率
} else if (value > numFrequency.get(pq.peek())) {
// 先删除堆首的元素
pq.remove();
// 再添加当前元素
pq.add(key);
}
});
Expand Down

0 comments on commit 4e84d98

Please sign in to comment.