Advertisement
exmkg

2-6

Jan 14th, 2025
34
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.87 KB | None | 0 0
  1. class Solution {
  2.     public int[][] construct2DArray(int[] original, int m, int n) {
  3.         if (original.length != m * n) {
  4.             // Impossible. Return an empty 2D array.
  5.             return new int[0][0];
  6.         }
  7.         int[][] result = new int[m][n];
  8.         for (int i = 0; i < original.length; i++) {
  9.             result[i / n][i % n] = original[i];
  10.         }
  11.         return result;
  12.     }
  13. }
  14.  
  15.  
  16.  
  17. class Solution {
  18.     public int[][] construct2DArray(int[] original, int m, int n) {
  19.         if (original.length != m * n) {
  20.             return new int[0][0];
  21.         }
  22.         int[][] arr = new int[m][n];
  23.         int current_index = 0;
  24.         for (int i = 0; i < m; i++) {
  25.             for (int j = 0; j < n; j++) {
  26.                 arr[i][j] = original[current_index];
  27.                 current_index++;
  28.             }
  29.         }
  30.         return arr;
  31.     }
  32. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement