@@ -89,4 +89,45 @@ public:
89
89
}
90
90
};
91
91
92
- ````
92
+ ```
93
+
94
+ #### Java
95
+
96
+ ```java
97
+
98
+ public class Solution {
99
+
100
+ public static int[][] construct2DArray(int[] original, int m, int n) {
101
+ // Check if the total number of elements in the original array equals m * n
102
+ if (original.length != m * n) {
103
+ return new int[0][0]; // Return an empty 2D array if it's impossible to form the 2D array
104
+ }
105
+
106
+ // Initialize the 2D array with the specified number of rows and columns
107
+ int[][] result = new int[m][n];
108
+
109
+ // Fill the 2D array with elements from the original array
110
+ for (int i = 0; i < original.length; i++) {
111
+ result[i / n][i % n] = original[i];
112
+ }
113
+
114
+ // Return the constructed 2D array
115
+ return result;
116
+ }
117
+
118
+ public static void main(String[] args) {
119
+ // Test cases
120
+ int[] original1 = {1, 2, 3, 4};
121
+ int m1 = 2, n1 = 2;
122
+ System.out.println(Arrays.deepToString(construct2DArray(original1, m1, n1)));
123
+
124
+ int[] original2 = {1, 2, 3};
125
+ int m2 = 1, n2 = 3;
126
+ System.out.println(Arrays.deepToString(construct2DArray(original2, m2, n2)));
127
+
128
+ int[] original3 = {1, 2};
129
+ int m3 = 1, n3 = 1;
130
+ System.out.println(Arrays.deepToString(construct2DArray(original3, m3, n3)));
131
+ }
132
+ }
133
+ ```
0 commit comments