2016-03-26 48 views
1

我正在嘗試使用優先級隊列的程序。當我將優先級隊列設置爲私有時,出現錯誤說明在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; 
    } 
} 
+0

確保你做出正確的文件(保存正確)。因爲源代碼中沒有'private'符號。 –

回答

2

不能在本地variable.The變量queue你在這裏創建的局部變量使用access specifier