制作优先级队列会给java带来错误

时间:2016-03-26 11:10:30

标签: java priority-queue

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

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;
    }
}

1 个答案:

答案 0 :(得分:2)

你不能在局部变量上使用access specifier。你在这里创建的变量queue是局部变量。

相关问题