1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| class Solution { public int kthSmallest(int[][] matrix, int k) { int n = matrix.length; int left = matrix[0][0], right = matrix[n - 1][n - 1]; while (left < right) { int mid = left + ((right - left) >> 1); if (check(matrix, k, mid, n)) right = mid; else left = mid + 1; } return left; } private boolean check(int[][] matrix, int k, int mid, int n) { int i = n - 1, j = 0, cnt = 0; while (i >= 0 && j < n) { if (matrix[i][j] <= mid) { cnt += i + 1; ++j; } else { --i; } } return cnt >= k; } }
|