-
Notifications
You must be signed in to change notification settings - Fork 0
/
378.有序矩阵中第k小的元素.js
55 lines (45 loc) · 1.14 KB
/
378.有序矩阵中第k小的元素.js
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/*
* @lc app=leetcode.cn id=378 lang=javascript
*
* [378] 有序矩阵中第K小的元素
*/
/**
* @param {number[][]} matrix
* @param {number} k
* @return {number}
*/
var kthSmallest = function (matrix, k) {
if (matrix.length === 1) return matrix[0][0];
let len = matrix.length;
let min = matrix[0][0];
let max = matrix[len - 1][len - 1];
while (min <= max) {
let mid = (max + min) >> 1;// 右移一位,即取平均数
let count = getCountLessThan(matrix, mid);
count < k ? min = mid + 1 : max = mid - 1;
console.log(min, mid, max, count, k)
}
return min;
};
/**在题中的矩阵中找到所有比target小的数的数量
*
* @param matrix
* @param target
* @returns {number}
*/
function getCountLessThan (matrix, target) {
let count = 0;
let len = matrix.length;
let x = len - 1;
let y = 0;
while (x >= 0 && y < len) {
//找到当前列第一个大于target的数的index
matrix[x][y] > target ? x-- : (count += x + 1, y++);
}
return count;
}
console.log(kthSmallest([
[1, 5, 9],
[10, 11, 13],
[12, 13, 15]
], 8))