2022. Convert a one-dimensional array to a two-dimensional array
1, dry
You are given a one-dimensional array of integers original with subscripts starting at 0 and two integers m and n. You need to create a two-dimensional array with m rows and n columns using all the elements in Original.
Elements with subscripts 0 to n-1 (both included) in Original form the first row of the two-dimensional array, elements with subscripts n to 2 * n-1 (both included) form the second row of the two-dimensional array, and so on.
Return a two-dimensional array of m x n as described above. If such a two-dimensional array is not possible, return an empty two-dimensional array.
Example 1:
Input:Original = [1,2,3,4], m = 2, n = 2
Output:[[1, 2], [3, 4]]
Explanation:
The constructed two-dimensional array should contain two rows and two columns.
The first part of original with n=2 is [1,2], which forms the first row of the two-dimensional array.
The second n=2 part of original is [3,4], which forms the second row of the two-dimensional array.
Example 2:
Input: original = [1,2,3], m = 1, n = 3 output: [[1,2,3] explanation: The constructed two-dimensional array should contain 1 row and 3 columns. Place all three elements from Original in the first line to form the desired two-dimensional array.
Example 3:
Input: original = [1,2], m = 1, n = 1 Output: [] Explanation: Original has 2 elements. Unable to fit 2 elements into a 1×1 two-dimensional array, returns an empty two-dimensional array.
Example 4:
Input: original = [3], m = 1, n = 2 Output: [] Explanation: Original has only 1 element. Unable to fill a 1×2 two-dimensional array with 1 element, return an empty two-dimensional array.
Tip:
1 <= original.length <= 5 * 10^4
1 <= original[i] <= 10^5
1 <= m, n <= 4 * 10^4
2
Look at the basic array operations
3, code,
var construct2DArray = function (original, m, n) {
returnoriginal.length ! == m * n ? [] :new Array(m).fill(0).map((v, i) = > {
return original.slice(n * i, n * i + n);
});
};
Copy the code
4. Execution results
Original link: leetcode-cn.com/problems/co…