Kth smallest element in sorted matrix

后端 未结 9 2218
被撕碎了的回忆
被撕碎了的回忆 2020-12-23 14:43

This is an interview question.

Find the Kth smallest element in a matrix with sorted rows and columns.
Is it correct that the Kth small

9条回答
  •  清歌不尽
    2020-12-23 15:38

    As people mentioned previously the easiest way is to build a min heap. Here's a Java implementation using PriorityQueue:

    private int kthSmallestUsingHeap(int[][] matrix, int k) {
    
        int n = matrix.length;
    
        // This is not necessary since this is the default Int comparator behavior
        Comparator comparator = new Comparator() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o1 - o2;
            }
        };
    
        // building a minHeap
        PriorityQueue pq = new PriorityQueue<>(n*n, comparator);
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                pq.add(matrix[i][j]);
            }
        }
    
        int ans = -1;
        // remove the min element k times
        for (int i = 0; i < k; i++) {
            ans = pq.poll();
        }
    
        return ans;
    }
    

提交回复
热议问题