Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java PriorityQueue算法搜索最小k值返回错误结果_Java_Algorithm_Priority Queue - Fatal编程技术网

Java PriorityQueue算法搜索最小k值返回错误结果

Java PriorityQueue算法搜索最小k值返回错误结果,java,algorithm,priority-queue,Java,Algorithm,Priority Queue,我试图找到数组的最小第k个值。我使用priorityQueue数据结构删除大于k的值,但返回的结果不正确。我的代码如下: public class Main2 { PriorityQueue<Integer> maxHeap = new PriorityQueue<Integer>(); public int smallestK(int[] arr, int k) { for(int num : arr) {

我试图找到数组的最小第k个值。我使用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);
    }
}
公共类Main2{
PriorityQueue maxHeap=new PriorityQueue();
公共整数smallestK(整数[]arr,整数k){
for(int num:arr){
添加(num);
if(maxHeap.size()>k){
maxHeap.poll();
}
}
返回maxHeap.peek();
}
公共静态void main(字符串[]args){
int arr[]={12,3,5,7,4,19,26};
Main2最小值=新Main2();
int result=minimate.smallestK(arr,3);//应返回5,但返回12
系统输出打印项次(结果);
}
}

如何修复算法以返回正确的结果?

您没有创建最大堆,而是创建最小堆。要创建最大堆,需要将比较器传递给PriorityQueue构造函数:

PriorityQueue<Integer> maxHeap = new PriorityQueue<Integer>(Collections.reverseOrder());
PriorityQueue maxHeap=newpriorityqueue(Collections.reverseOrder());

@JanezKuhar按照您的建议,在修剪队列之前,无需完全填满队列。非常感谢!我只是在学习Java,所以我认为它是一个最大堆,顺便问一下,运行Collections.reverseOrder()会改变它的复杂性,还是与最小堆的复杂性相同?复杂性保持不变。一个比较需要恒定的时间。@trincot只是想知道在优先级队列中插入元素的时间复杂度是多少,因为我们正在构建和执行heapify?请查看上的时间复杂度表。您可以假设Java的PriorityQueue是作为二进制堆实现的。如果您还有其他问题,请毫不犹豫地发布新问题(除非以前有人问过)。