Skip to content

Commit 89db8e8

Browse files
authored
Create 1439-find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows.js
1 parent 7e0cf25 commit 89db8e8

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/**
2+
* @param {number[][]} mat
3+
* @param {number} k
4+
* @return {number}
5+
*/
6+
const kthSmallest = function(mat, k) {
7+
let lo = 0;
8+
let hi = 0;
9+
for(let r of mat) {
10+
lo += r[0];
11+
hi += r[r.length-1];
12+
}
13+
14+
const check = (row, sum, limit) => {
15+
if (sum > limit) return 0;
16+
if (row === mat.length) return 1;
17+
let totalcnt = 0;
18+
for(let v of mat[row]) {
19+
let cnt = check(row+1, v+sum, limit);
20+
totalcnt += cnt;
21+
if (cnt === 0 || totalcnt > k) break;
22+
}
23+
24+
return totalcnt;
25+
};
26+
27+
while(lo <= hi) {
28+
let m = Math.floor((lo+hi)/2);
29+
let cnt = check(0,0,m);
30+
if (cnt < k) {
31+
lo = m+1;
32+
} else {
33+
hi = m-1;
34+
}
35+
}
36+
37+
return lo;
38+
};

0 commit comments

Comments
 (0)