繁体   English   中英

进行优先级队列会导致Java错误

[英]Making a priority queue gives error in java

我正在尝试使用优先级队列的程序。 将优先级队列设为私有时,出现错误消息

KthSmallestPQ.java:8: error: illegal start of expression
            private PriorityQueue<MatrixElement> queue = new PriorityQueue<MatrixElement>(a[0].length, new Comparator<MatrixElement>() {
            ^

当我删除私有代码时,代码将编译并运行。 有人可以解释为什么将PQ设为私有会导致错误吗?

这是有效的代码:

import java.util.*;

class KthSmallestPQ {
    public static int findKthLow(int[][] a, int k) {
        if(k < 0 || k >= a.length * a[0].length)
            return Integer.MAX_VALUE;

        PriorityQueue<MatrixElement> queue = new PriorityQueue<MatrixElement>(a[0].length, new Comparator<MatrixElement>() { 
            public int compare(MatrixElement first, MatrixElement second) {
                return first.value - second.value;
            }
        });

        for(int i = 0; i < a[0].length; i++)
            queue.add(new MatrixElement(a[0][i], 0, i));

        MatrixElement lowest = null;

        for(int i = 0; i < k; i++) {
            lowest = queue.remove();

        // add element from the next row of same column to the priority queue
            int row = lowest.row + 1;
            int col = lowest.col;

            if(row < a.length)
                queue.add(new MatrixElement(a[row][col], row, col));
            else
                queue.add(new MatrixElement(Integer.MAX_VALUE, row, col));
        }

    return lowest.value;
}

    public static void main(String[] args) {
        int[][] matrix = {{10, 20, 30, 40},
                {15, 25, 35, 45},
                {24, 29, 37, 48},
                {32, 33, 39, 50}};

        int k = 6;
        System.out.println(k + "th smallest value is: " + findKthLow(matrix, k));
    }
}
class MatrixElement {
    int value;
    int row;
    int col;

    MatrixElement(int value, int row, int col) {
        this.value = value;
        this.col = col;
        this.row = row;
    }
}

您不能对局部变量使用access specifier 。您在此处创建的变量queue是局部变量。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM