题解 | #有序矩阵中第K小的元素#
有序矩阵中第K小的元素
https://www.nowcoder.com/practice/07b66536f3f94f88908fe598108172d5
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // 读取输入 int k = scanner.nextInt(); int n = scanner.nextInt(); int[][] matrix = new int[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { matrix[i][j] = scanner.nextInt(); } } // 解决问题并输出结果 int result = kthSmallest(matrix, k); System.out.println(result); scanner.close(); } // 寻找矩阵中第k小的元素 public static int kthSmallest(int[][] matrix, int k) { int n = matrix.length; int left = matrix[0][0]; int right = matrix[n - 1][n - 1]; while (left < right) { int mid = left + (right - left) / 2; int count = countLessOrEqual(matrix, mid); if (count < k) { left = mid + 1; } else { right = mid; } } return left; } // 计算矩阵中小于等于target的元素个数 private static int countLessOrEqual(int[][] matrix, int target) { int n = matrix.length; int count = 0; int row = n - 1; int col = 0; while (row >= 0 && col < n) { if (matrix[row][col] <= target) { count += (row + 1); col++; } else { row--; } } return count; } }