Clean java solution


  • 0
    Z

    public class Solution {
    public int kthSmallest(int[][] matrix, int k) {
    int m = matrix.length , n = matrix[0].length , i, j;

        PriorityQueue<Integer> pq = new PriorityQueue<>(k , new Comparator<Integer>(){
            public int compare(Integer i1, Integer i2) {
                return i2.intValue() - i1.intValue();
            }    
        });
        
        for(i=0;i<m;i++) {
            for(j=0;j<n;j++) {
                if(pq.size() < k) {
                    pq.add(matrix[i][j]);
                } else if(matrix[i][j] < pq.peek()) {
                    pq.poll();
                    pq.add(matrix[i][j]);
                }
            }
        }
        
        return pq.peek();
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.