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

    原文作者:Richardo92
    原文地址: https://www.jianshu.com/p/902e13f7eee5#comments
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞