| Conditions | 8 |
| Paths | 4 |
| Total Lines | 32 |
| Code Lines | 22 |
| Lines | 0 |
| Ratio | 0 % |
| Changes | 1 | ||
| Bugs | 0 | Features | 0 |
| 1 | <?php |
||
| 28 | public static function kthSmallest2(array $matrix, int $k): int |
||
| 29 | { |
||
| 30 | if (empty($matrix) || $k <= 0) { |
||
| 31 | return 0; |
||
| 32 | } |
||
| 33 | [$m, $n] = [count($matrix), count($matrix[0])]; |
||
| 34 | [$low, $high] = [$matrix[0][0], $matrix[$m - 1][$n - 1]]; |
||
| 35 | $helper = static function (array $matrix, int $target) { |
||
| 36 | $n = count($matrix); |
||
| 37 | [$cnt, $i, $j] = [0, $n - 1, 0]; |
||
| 38 | while ($i >= 0 && $j < $n) { |
||
| 39 | if ($matrix[$i][$j] > $target) { |
||
| 40 | $i--; |
||
| 41 | } else { |
||
| 42 | $cnt += ($i + 1); |
||
| 43 | $j++; |
||
| 44 | } |
||
| 45 | } |
||
| 46 | return $cnt; |
||
| 47 | }; |
||
| 48 | |||
| 49 | while ($low < $high) { |
||
| 50 | $mid = (int)(($high - $low) / 2) + $low; |
||
| 51 | $cnt = $helper($matrix, $mid); |
||
| 52 | if ($cnt < $k) { |
||
| 53 | $low = $mid + 1; |
||
| 54 | } else { |
||
| 55 | $high = $mid - 1; |
||
| 56 | } |
||
| 57 | } |
||
| 58 | |||
| 59 | return $low; |
||
| 60 | } |
||
| 62 |