Leetcode 2022. Convert 1D Array Into 2D Array
You are given a 1D array original
and two integers m
and n
. You are tasked with creating a 2D array with m
rows and n
columns using all the elements from the original
array.
More formally, the transformed array should be such that:
Example:
Input: original = [1,2,3,4], m = 2, n = 2
Output: [[1,2],[3,4]]
Input: original = [1,2,3], m = 1, n = 3
Output: [[1,2,3]]
Input: original = [1,2], m = 1, n = 1
Output: []
Input: original = [3], m = 1, n = 1
Output: [[3]]
original
array need to be unique?
To solve this problem, the following steps can be taken:
m x n
2D array if and only if the length of original
is exactly m * n
.m x n
.public class Solution {
public int[][] construct2DArray(int[] original, int m, int n) {
int length = original.length;
// Check if the transformation is feasible
if (length != m * n) {
return new int[0][];
}
int[][] result = new int[m][n];
for (int i = 0; i < length; i++) {
result[i / n][i % n] = original[i];
}
return result;
}
}
original
array is accessed and placed exactly once in the resulting 2D array.This problem involves straightforward looping and index calculations, making it efficient for the given constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?