赞
踩
1、堆是一颗完全二叉树;
2、堆中的某个结点的值总是大于等于(最大堆)或小于等于(最小堆)其孩子结点的值。
3、堆中每个结点的子树都是堆树。
PriorityQueue<Integer> pq = new PriorityQueue<>();
java的优先队列数据结构,默认是小顶堆。最小元素在堆顶
- public int kthSmallest(int[][] matrix, int k) {
- // Queue<Integer> queue = new PriorityQueue<Integer>() {
- // public int compare(Integer o1, Integer o2) {
- // return o2 - o1;
- // }
- // };//大顶堆
- Queue<Integer> queue = new PriorityQueue<Integer>((o1, o2) -> (o2 - o1));
- for (int i = 0; i < matrix.length; i++) {
- for (int j = 0; j < matrix[0].length; j++) {
- queue.offer(matrix[i][j]);
- if (queue.size() > k) {
- queue.poll();
- }
- }
- }
- return queue.peek();
-
- }

- public int findKthLargest(int[] nums, int k) {
- PriorityQueue<Integer> pq = new PriorityQueue<>();
- for (int ele : nums){
- pq.offer(ele);
- if (pq.size() > k) {
- pq.poll();
- }
- }
- return pq.peek();
- }
- public int[] topKFrequent(int[] nums, int k) {
- int[] res = new int[k];
- //小顶堆
- HashMap<Integer, Integer> map = new HashMap<>();
- 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);
- }
- // map.put(nums[i], map.getOrDefault(map.get(nums[i]), 0) + 1);
- }
- //按照频率排序
- Queue<Integer> queue = new PriorityQueue<>((o1, o2) -> (map.get(o1) - map.get(o2)));
- for (Integer elem : map.keySet()) {
- queue.add(elem);
- if (queue.size() > k) {
- queue.poll();
- }
- }
-
- int i = 0;
- while (!queue.isEmpty()) {
- res[i++] = queue.poll();
- }
- return res;
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。