Leetcode - Kth Smallest Element in a Sorted Matrix

My code:

public class Solution {
    public int kthSmallest(int[][] matrix, int k) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return -1;
        }
        
        PriorityQueue<Integer> pq = new PriorityQueue<Integer>(k, new Comparator<Integer>() {
            public int compare(Integer i1, Integer i2) {
                return -1 * (i1.compareTo(i2));
            }    
        });
        
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[0].length; j++) {
                if (pq.size() < k) {
                    pq.offer(matrix[i][j]);
                }
                else {
                    if (matrix[i][j] < pq.peek()) {
                        pq.poll();
                        pq.offer(matrix[i][j]);
                    }
                }
            }
        }
        
        return pq.peek();
    }
}

這道題目直接拿 map-heap 來解了。感覺效率也并不是很高。
可以再優化。
如果某一列的某個數字被彈出后,那么這一列剩下的數字都不可能進入這個堆,沒必要再試了。

My code:

public class Solution {
    private class Tuple {
        int row;
        int col;
        int val;
        Tuple(int row, int col, int val) {
            this.row = row;
            this.col = col;
            this.val = val;
        }
    }
    public int kthSmallest(int[][] matrix, int k) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return -1;
        }
        
        PriorityQueue<Tuple> pq = new PriorityQueue<Tuple>(k, new Comparator<Tuple>() {
            public int compare(Tuple i1, Tuple i2) {
                return -1 * (i1.val - i2.val);
            }    
        });
        boolean[] col = new boolean[matrix[0].length];
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[0].length; j++) {
                if (col[j]) {
                    continue;
                }
                if (pq.size() < k) {
                    Tuple t = new Tuple(i, j, matrix[i][j]);
                    pq.offer(t);
                }
                else {
                    if (matrix[i][j] < pq.peek().val) {
                        Tuple t = pq.poll();
                        pq.offer(new Tuple(i, j, matrix[i][j]));
                        col[t.col] = true;
                    }
                }
            }
        }
        
        return pq.peek().val;
    }
}

先這樣吧。

Anyway, Good luck, Richardo! -- 09/15/2016

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容