-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path378.php
43 lines (40 loc) · 922 Bytes
/
378.php
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
<?php
class Solution
{
/**
* @param Integer[][] $matrix
* @param Integer $k
* @return Integer
*/
public function kthSmallest($matrix, $k)
{
$n = count($matrix) - 1;
$l = $matrix[0][0];
$r = $matrix[$n][$n];
while ($l < $r) {
$mid = floor(($r - $l) / 2) + $l;
$count = $this->countLessThanMid($matrix, $mid, $n);
if ($count < $k) {
$l = $mid + 1;
} else {
$r = $mid;
}
}
return $r;
}
public function countLessThanMid($matrix, $mid, $n)
{
$i = $n;
$j = 0;
$count = 0;
while ($i >= 0 && $j <= $n) {
if ($matrix[$i][$j] <= $mid) {
$count += $i + 1;
$j++;
} else {
$i--;
}
}
return $count;
}
}