Created
October 15, 2017 07:00
-
-
Save krabello/72ea13440b27c3e1c5a4b695c6b6b32c to your computer and use it in GitHub Desktop.
Count Negative Integers in Row/Column-Wise Sorted Matrix
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function countNegatives($matrix) { | |
if (!is_array($matrix)) { | |
throw new TypeError('The matrix is not an array'); | |
} | |
//rows | |
$rows = count($matrix); | |
// columns | |
$columns = (array_sum(array_map('count', $matrix)) / $rows); | |
$count = 0; | |
$i = 0; | |
$j = $columns - 1; | |
$sortedMatrix = []; | |
foreach ($matrix as $row) { | |
sort($row, SORT_NUMERIC); | |
$sortedMatrix[] = $row; | |
} | |
while (($j >= 0) && ($i < $rows)) { | |
if ($sortedMatrix[$i][$j] < 0) { | |
$count += $j +1; | |
$i++; | |
} else { | |
$j--; | |
} | |
} | |
return $count; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment