# 378.Kth-Smallest-Element-in-a-Sorted-Matrix

## 378. Kth Smallest Element in a Sorted Matrix

## 题目地址

<https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/>

## 题目描述

```
Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix.

Note that it is the kth smallest element in the sorted order, not the kth distinct element.

Example:
matrix = [
   [ 1,  5,  9],
   [10, 11, 13],
   [12, 13, 15]
],
k = 8,
return 13.

Note:
You may assume k is always valid, 1 ≤ k ≤ n^2.
```

## 代码

### Approach #1 Recursive Approach

```java
class Solution {
  public int kthSmallest(int[][] matrix, int k) {
        int n = matrix.length;
    PriorityQueue<int[]> pq = new PriorityQueue<int[]>((a, b) -> a[2] - b[2]);
    for (int i = 0; i <= n - 1; i++) {
      pq.offer(new int[]{0, i, matrix[0][i]});
    }
    for (int j = 0; j < k - 1; j ++) {
         int[] tup = pq.poll();
      int r = tup[0];
      int c = tup[1];
      if (r == n - 1) continue;
      pq.offer(new int[] {r + 1, c, matrix[r + 1][c] });
    }
    return pq.poll()[2];
  }
}
```

### Approach #2 Binary Search

```java
class Soltuion {
  public int kthSmallest(int[][] matrix, int k) {
    int row = matrix.length - 1;
    int col = matrix[0].length - 1;
    int lo = matrix[0][0];
    int hi = matrix[row][col] + 1;
    while (lo < hi) {
      int mid = lo + (hi - lo) / 2;
      int count = 0, j = col;
      for (int i = 0; i < row; i++) {
        while (j >= 0 && matrix[i][j] > mid)    j--;
        count += (j + 1);
      }
      if (count < k) {
        lo = mid + 1;
      } else {
        hi = mid;
      }
    }

    return lo;
  }
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://wentao-shao.gitbook.io/leetcode/array/378.kth-smallest-element-in-a-sorted-matrix.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
