Kth smallest element in sorted matrix

后端 未结 9 2194
被撕碎了的回忆
被撕碎了的回忆 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

    O(k log(k)) solution.

    • Build a minheap.

    • Add (0,0) to the heap. While, we haven't found the kth smallest element, remove the top element (x,y) from heap and add next two elements [(x+1,y) and (x,y+1)] if they haven't been visited before.

    We are doing O(k) operations on a heap of size O(k) and hence the complexity.

    0 讨论(0)
  • 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<Integer> comparator = new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o1 - o2;
            }
        };
    
        // building a minHeap
        PriorityQueue<Integer> 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;
    }
    
    0 讨论(0)
  • 2020-12-23 15:38

    Kth smallest element in the matrix :

    The problem can be narrowed down as below.

    if k is 20, then take k*k matrix (where answer will definitely lie.)

    Now you can merge the rows in pair repeatedly to build a sorted array and then find the kth smallest number.

    0 讨论(0)
提交回复
热议问题