You won't find better than this :)


  • 0
    A

    public class Solution {
    public int kthSmallest(int[][] matrix, int k) {

        PriorityQueue<Integer> pq= new PriorityQueue(k, Collections.reverseOrder());
        
        for(int i=0;i<matrix.length;i++){
            for(int j=0;j<matrix[0].length;j++){
                if(pq.size()<k)
                    pq.add(matrix[i][j]);
                else{
                    int temp=pq.peek();
                    if(temp>matrix[i][j]){
                        pq.poll();
                        pq.offer(matrix[i][j]);
                    }
                }
            }
        }
        return pq.poll();
    }
    

    }


  • 1
    A

    This is nice and short, but it is O(n^2 log n) in the worst case. Both O(n log n) and O(k log k) are possible.


Log in to reply
 

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