1380. Lucky Numbers in a Matrix #72
-
Given an A lucky number is an element of the matrix such that it is the minimum element in its row and maximum in its column. Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
To solve this problem, we can follow these steps:
Let's implement this solution in PHP: 1380. Lucky Numbers in a Matrix <?PHP
/**
* @param Integer[][] $matrix
* @return Integer[]
*/
function luckyNumbers ($matrix) {
$m = count($matrix);
$n = count($matrix[0]);
$rowMins = [];
$colMaxs = array_fill(0, $n, PHP_INT_MIN);
// Find the minimum in each row
for ($i = 0; $i < $m; $i++) {
$rowMins[$i] = PHP_INT_MAX;
for ($j = 0; $j < $n; $j++) {
if ($matrix[$i][$j] < $rowMins[$i]) {
$rowMins[$i] = $matrix[$i][$j];
}
}
}
// Find the maximum in each column
for ($j = 0; $j < $n; $j++) {
for ($i = 0; $i < $m; $i++) {
if ($matrix[$i][$j] > $colMaxs[$j]) {
$colMaxs[$j] = $matrix[$i][$j];
}
}
}
$luckyNumbers = [];
// Check for lucky numbers
for ($i = 0; $i < $m; $i++) {
for ($j = 0; $j < $n; $j++) {
if ($matrix[$i][$j] == $rowMins[$i] && $matrix[$i][$j] == $colMaxs[$j]) {
$luckyNumbers[] = $matrix[$i][$j];
}
}
}
return $luckyNumbers;
}
// Example usage:
$matrix1 = [[3,7,8],[9,11,13],[15,16,17]];
$matrix2 = [[1,10,4,2],[9,3,8,7],[15,16,17,12]];
$matrix3 = [[7,8],[1,2]];
print_r(luckyNumbers($matrix1)); // Output: [15]
print_r(luckyNumbers($matrix2)); // Output: [12]
print_r(luckyNumbers($matrix3)); // Output: [7]
?> Explanation:
This approach ensures that we correctly identify all lucky numbers in the matrix with a time complexity of (O(m \times n)), which is efficient for the given constraints. |
Beta Was this translation helpful? Give feedback.
To solve this problem, we can follow these steps:
Let's implement this solution in PHP: 1380. Lucky Numbers in a Matrix