Skip to content

Commit 33fde5a

Browse files
authored
Merge pull request codeharborhub#2726 from ananyag309/main
Added lc soln of 2022-convert-1d-array-into-2d-array
2 parents 587dceb + 8f18e26 commit 33fde5a

File tree

1 file changed

+42
-1
lines changed

1 file changed

+42
-1
lines changed

dsa-solutions/lc-solutions/2000-2099/2022-convert-1d-array-into-2d-array.md

Lines changed: 42 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -89,4 +89,45 @@ public:
8989
}
9090
};
9191

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

Comments
 (0)