2022. Convert 1D Array Into 2D Array #450
-
Topics: You are given a 0-indexed 1-dimensional (1D) integer array The elements from indices Return an Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to follow these steps:
Let's implement this solution in PHP: 2022. Convert 1D Array Into 2D Array <?php
/**
* @param Integer[] $original
* @param Integer $m
* @param Integer $n
* @return Integer[][]
*/
function construct2DArray($original, $m, $n) {
$length = count($original);
// Check if the total number of elements matches m * n
if ($length != $m * $n) {
return []; // Return an empty array if it's impossible
}
$result = array();
$index = 0;
// Populate the 2D array
for ($i = 0; $i < $m; $i++) {
$row = array();
for ($j = 0; $j < $n; $j++) {
$row[] = $original[$index];
$index++;
}
$result[] = $row;
}
return $result;
}
// Example usage:
//Example 1
$original = array(1, 2, 3, 4);
$m = 2;
$n = 2;
print_r(construct2DArray($original, $m, $n)); //Output: [[1,2],[3,4]]
//Example 2
$original = array(1, 2, 3);
$m = 1;
$n = 3;
print_r(construct2DArray($original, $m, $n)); //Output: [[1,2,3]]
//Example 3
$original = array(1, 2);
$m = 1;
$n = 1;
print_r(construct2DArray($original, $m, $n)); //Output: []
?> Explanation:
Example Output:For the provided example: $original = array(1, 2, 3, 4);
$m = 2;
$n = 2;
print_r(construct2DArray($original, $m, $n)); The output will be: Array
(
[0] => Array
(
[0] => 1
[1] => 2
)
[1] => Array
(
[0] => 3
[1] => 4
)
) This approach ensures that the 1D array is correctly converted into the desired 2D array, and it efficiently handles edge cases by checking whether the conversion is possible. |
Beta Was this translation helpful? Give feedback.
We need to follow these steps:
Check if Conversion is Possible: The conversion from a 1D array to a 2D array is only possible if the total number of elements in the 1D array (
original.length
) is exactly equal tom * n
, wherem
is the number of rows andn
is the number of columns. If this condition is not met, return an empty array.Create the 2D Array: If the conversion is possible, initialize a 2D array with
m
rows andn
columns, and populate it by iterating over the 1D array and filling in the 2D array row by row.Let's implement this solution in PHP: 2022. Convert 1D Array Into 2D Array