java - 搜索最小 k 值的 PriorityQueue 算法返回不正确的结果
问题描述
我正在尝试找到数组的最小 kth 值。我使用了一个 priorityQueue 数据结构来删除大于 k 的值,但是我返回了一个不正确的结果。我的代码如下:
public class Main2 {
PriorityQueue<Integer> maxHeap = new PriorityQueue<Integer>();
public int smallestK(int[] arr, int k) {
for(int num : arr) {
maxHeap.add(num);
if(maxHeap.size() > k) {
maxHeap.poll();
}
}
return maxHeap.peek();
}
public static void main(String[] args) {
int arr[] = { 12, 3, 5, 7, 4, 19, 26 };
Main2 smallest = new Main2();
int result = smallest.smallestK(arr, 3); //should return 5, but returns 12
System.out.println(result);
}
}
如何修复算法以返回正确的结果?
解决方案
您没有创建最大堆,而是创建了最小堆。要创建最大堆,您需要将比较器传递给 PriorityQueue 构造函数:
PriorityQueue<Integer> maxHeap = new PriorityQueue<Integer>(Collections.reverseOrder());
推荐阅读
- google-maps - 使用 Google Maps API 查找与街道地址相关联的商家名称?
- google-sheets - Google表格:如何在OR比较是字符串的情况下对多个条件(OR的AND)求和?
- php - Resful API json_decode(file_get_contents("php://input")); 总是返回 null
- excel - 具有动态内容的 Excel 下拉菜单
- bash - 如何通过 curl --binary-data 和 webkit 表单边界上传文件?
- javascript - 将 2 个数组参数传递给 wasm
- microcontroller - 无法使用 ESP32 (esp-idf) 处理 nRF24L01+
- xamarin.forms - 如何使用 BoxView 分隔网格中的两个元素?
- android - Flutter Navigation push 替换没有放在第一个活动中时不起作用
- python-2.7 - 在 uwsgi 服务器上运行的 Flask 应用程序无法加载属性文件