当前位置:   article > 正文

优先队列 小顶堆,大顶堆_优先队列是最小堆还是最大堆呢

优先队列是最小堆还是最大堆呢

 

 

堆定义

1、堆是一颗完全二叉树

2、堆中的某个结点的值总是大于等于(最大堆)或小于等于(最小堆)其孩子结点的值。

3、堆中每个结点的子树都是堆树。

PriorityQueue<Integer> pq = new PriorityQueue<>(); 

java的优先队列数据结构,默认是小顶堆。最小元素在堆顶

第k小的值,则需要一个大顶堆

378. 有序矩阵中第 K 小的元素

  1. public int kthSmallest(int[][] matrix, int k) {
  2. // Queue<Integer> queue = new PriorityQueue<Integer>() {
  3. // public int compare(Integer o1, Integer o2) {
  4. // return o2 - o1;
  5. // }
  6. // };//大顶堆
  7. Queue<Integer> queue = new PriorityQueue<Integer>((o1, o2) -> (o2 - o1));
  8. for (int i = 0; i < matrix.length; i++) {
  9. for (int j = 0; j < matrix[0].length; j++) {
  10. queue.offer(matrix[i][j]);
  11. if (queue.size() > k) {
  12. queue.poll();
  13. }
  14. }
  15. }
  16. return queue.peek();
  17. }

第k大,则需要小顶堆

215. 数组中的第K个最大元素

  1. public int findKthLargest(int[] nums, int k) {
  2. PriorityQueue<Integer> pq = new PriorityQueue<>();
  3. for (int ele : nums){
  4. pq.offer(ele);
  5. if (pq.size() > k) {
  6. pq.poll();
  7. }
  8. }
  9. return pq.peek();
  10. }

 347. 前 K 个高频元素

  1. public int[] topKFrequent(int[] nums, int k) {
  2. int[] res = new int[k];
  3. //小顶堆
  4. HashMap<Integer, Integer> map = new HashMap<>();
  5. for (int i = 0; i < nums.length; i++) {
  6. if (map.containsKey(nums[i])) {
  7. map.put(nums[i], map.get(nums[i]) + 1);
  8. } else {
  9. map.put(nums[i], 1);
  10. }
  11. // map.put(nums[i], map.getOrDefault(map.get(nums[i]), 0) + 1);
  12. }
  13. //按照频率排序
  14. Queue<Integer> queue = new PriorityQueue<>((o1, o2) -> (map.get(o1) - map.get(o2)));
  15. for (Integer elem : map.keySet()) {
  16. queue.add(elem);
  17. if (queue.size() > k) {
  18. queue.poll();
  19. }
  20. }
  21. int i = 0;
  22. while (!queue.isEmpty()) {
  23. res[i++] = queue.poll();
  24. }
  25. return res;
  26. }

 

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/355156
推荐阅读
相关标签
  

闽ICP备14008679号