378. Kth Smallest Element in a Sorted Matrix
Leetcode
題目
解答
var kthSmallest = function(matrix, k) {
const n = matrix.length;
function getCntLowerThen(value) {
let cnt = 0;
let row = n - 1;
let col = 0;
while (row >= 0 && col < n) {
if (matrix[row][col] <= value) {
cnt += row + 1;
col++;
} else {
row--;
}
}
return cnt;
}
let start = matrix[0][0];
let end = matrix[n - 1][n - 1];
while (start < end) {
const mid = Math.floor((start + end) / 2);
const cnt = getCntLowerThen(mid);
if (cnt < k) {
start = mid + 1;
} else {
end = mid;
}
}
return start;
}測資
參考資料
Last updated