Description
Find the kth smallest number in a row and column sorted matrix.
Each row and each column of the matrix is incremental.
Example
Example 1:
Input:
[
[1 ,5 ,7],
[3 ,7 ,8],
[4 ,8 ,9],
]
k = 4
Output: 5
Example 2:
Input:
[
[1, 2],
[3, 4]
]
k = 3
Output: 3
Challenge
O*(klogn*) time, n is the maximum of the width and height of the matrix.
Ideas:
You may be used in the binary heap or O ( klogn solve problems in time complexity) of.
With a heap solve:
Define a small heap root, starting only into the first row of the first column elements.
Cycle K K times, each time taken element, then that element to the right and below the element into the heap of K K is the time taken to answer elements.
Wherein an element does not pay attention to the repeated stack needs to be recorded.
dichotomy:
Binary answer, i.e. the initial interval matrix composed of minimum and maximum interval.
Find the midpoint of the interval binary process in mid matrix rank is assumed to be t
- If t == k, i.e., the point is the result
- If t> k, into the interval [l, mid - 1]
- If t <k, into the interval [mid + 1, r]
public class Solution { /** * @param matrix: a matrix of integers * @param k: An integer * @return: the kth smallest number in the matrix */ class Pair { public int x, y, val; public Pair(int x, int y, int val) { this.x = x; this.y = y; this.val = val; } } class PairComparator implements Comparator<Pair> { public int compare(Pair a, Pair b) { return a.val - b.val; } } public int kthSmallest(int[][] matrix, int k) { int[] dx = new int[]{0, 1}; int[] dy = new int[]{1, 0}; int n = matrix.length; int m = matrix[0].length; boolean[][] hash = new boolean[n][m]; PriorityQueue<Pair> minHeap = new PriorityQueue<Pair>(k, new PairComparator()); minHeap.add(new Pair(0, 0, matrix[0][0])); for (int i = 0; i < k - 1; i++) { Pair cur = minHeap.poll(); for (int j = 0; j < 2; j++) { int next_x = cur.x + dx[j]; int next_y = cur.y + dy[j]; Pair next_Pair = new Pair(next_x, next_y, 0); if (next_x < n && next_y < m && !hash[next_x][next_y]) { hash[next_x][next_y] = true; next_Pair.val = matrix[next_x][next_y]; minHeap.add(next_Pair); } } } Return minHeap.peek (). Val; } }