Java 0ms 100% Faster - 🍍 vs🍍🍍 Loops - Detailed Explanation
\n\nHere are two solutions to this problem. One uses two loops, the other uses a single loop. The winner is announced at the end.\n# 2 Loops \uD83C\uDF4D\uD83C\
![image](https://assets.leetcode.com/users/images/9f25e6a9-328b-4b7c-8a55-2ac7e0103107_1666241352.6408157.png)\n\nHere are two solutions to this problem. One uses two loops, the other uses a single loop. The winner is announced at the end.\n# 2 Loops \uD83C\uDF4D\uD83C\uDF4D \n```\n/**\n * Reshape the Matrix\n * In MATLAB, there is a handy function called reshape which can reshape an m x n matrix into a new\n * one with a different size r x c keeping its original data.\n *\n * You are given an m x n matrix mat and two integers r and c representing the number of rows and\n * the number of columns of the wanted reshaped matrix.\n *\n * The reshaped matrix should be filled with all the elements of the original matrix in the same\n * row-traversing order as they were.\n *\n * If the reshape operation with given parameters is possible and legal, output the new reshaped\n * matrix; Otherwise, output the original matrix.\n * \n * Constraints:\n * m == mat.length\n * n == mat[i].length\n * 1 <= m, n <= 100\n * -1000 <= mat[i][j] <= 1000\n * 1 <= r, c <= 300\n */\nclass Solution {\n    /*\n     * To fill in the reshaped \'ret\' matrix, this algorithm has two loops. The outer loop\n     * iterates over the rows of mat; the inner loop iterates over the cols of mat.\n     *\n     * Example:\n     *\n     *                                        row 0   1\n     *                                      col ---------\n     *         row 0   1   2                 0  | a | b |\n     *       col  ------------                  |-------|\n     *        0  | a | b | c |               1  | c | d |\n     *           |-----------|   ------->       |-------|\n     *        1  | d | e | f |               2  | e | f |\n     *            -----------                   |-------|\n     *\n     *           mat matrix                    ret matrix\n     *         mr = 1, mc = 3                  r = 3, c = 2\n     *\n     *\n     *        -------- mat --------------    ------- ret ----------------\n     *  i j k     mat[i][j]                  ret[k/c][k%c]\n     *  - - - ---------------------------    ----------------------------\n     *  0 0 0     mat[0,0] = a           --> ret[0/2][0/2] = ret[0][0]\n     *  0 1 1     mat[0,1] = b           --> ret[1/2][1/2] = ret[0][1]\n     *  0 2 2     mat[0,2] = c           --> ret[2/2][2/2] = ret[1][0]\n     *  1 0 3     mat[1,0] = d           --> ret[3/2][3/2] = ret[1][1]\n     *  1 1 4     mat[1,1] = e           --> ret[4/2][4/2] = ret[2][0]\n     *  1 2 5     mat[1,2] = f           --> ret[5/2][5/2] = ret[2][1]\n     *\n     * The total number of division operations of the two loops is n * 2,\n     * where n = mr * mc. This is half as many division operations as the\n     * single-loop version below.\n     */\n\tpublic int[][] matrixReshape(final int[][] mat, final int r, final int c) {\n         final int mr = mat.length;\n         final int mc =  mat[0].length;\n         final int n =  mr * mc;\n\n        // check arguments\n        if (r * c != n) {\n            return mat;\n        }\n\n         // create reshaped matrix\n         final int[][] ret = new int[r][c];\n         int k = 0; // number of cells filled in so far\n         for (int i = 0; i < mr; i++) {\n             for (int j = 0; j < mc; j++) {\n                 ret[k / c][k % c] = mat[i][j]; // see explanation above\n                 k++;\n             }\n         }\n         return ret;\n     }\n```\n---\n# Single Loop \uD83C\uDF4D\n```\n/*\n * To fill in the reshaped \'ret\' matrix, this algorithm iterates over n elements\n * where n is the rows multiplied by the columns.\n *\n * Example:\n *\n *                                        row 0   1\n *                                      col ---------\n *         row 0   1   2                 0  | a | b |\n *       col  ------------                  |-------|\n *        0  | a | b | c |               1  | c | d |\n *           |-----------|   ------->       |-------|\n *        1  | d | e | f |               2  | e | f |\n *            -----------                   |-------|\n *\n *           mat matrix                    ret matrix\n *         mr = 1, mc = 3                  r = 3, c = 2\n *\n *\n *    ----------- mat ------------     ----------- mat ------------\n *  i      mat[i/mc][i%mc]             ret[i/c][i%c]\n *  - ----------------------------     ----------------------------\n *  0 mat[0/3][0%3] = mat[0,0] = a --> ret[0/2][0/2] = ret[0][0]\n *  1 mat[1/3][1%3] = mat[0,1] = b --> ret[1/2][1/2] = ret[0][1]\n *  2 mat[2/3][2%3] = mat[0,2] = c --> ret[2/2][2/2] = ret[1][0]\n *  3 mat[3/3][3%3] = mat[1,0] = d --> ret[3/2][3/2] = ret[1][1]\n *  4 mat[4/3][4%3] = mat[1,1] = e --> ret[4/2][4/2] = ret[2][0]\n *  5 mat[5/3][5%3] = mat[1,2] = f --> ret[5/2][5/2] = ret[2][1]\n *\n * The total number of division operations of the single loop is n * 4,\n * where n = mr * mc. This is twice as many division operations as the\n * double-loop version above.\n */\n    public int[][] matrixReshape(final int[][] mat, final int r, final int c) {\n        final int mr = mat.length;\n        final int mc =  mat[0].length;\n        final int n =  mr * mc;\n\n        // check arguments\n        if (r * c != n) {\n            return mat;\n        }\n\n        // create reshaped matrix\n        final int[][] ret = new int[r][c];\n        for (int i = 0; i < n; i++) {\n            ret[i / c][i % c] = mat[i / mc][i % mc]; // see explanation above\n        }\n        return ret;\n    }\n}\n```\n---\n# Comparison\uD83C\uDF4Dvs \uD83C\uDF4D\uD83C\uDF4D\n\nBoth solutions iterate over n = r * c elements. The first solution pays the cost of having additional int variables j and k, but that allows it to save 2 division operations per iteration as compared to the second solution. Also, the first solution has less cognitive complexity imo. Based on these two factors, the winner is \uD83E\uDD41... 2 fruit loops!\n![image](https://assets.leetcode.com/users/images/59a34a35-c78f-4082-b31a-03d743ee8b88_1666242407.207343.png)\n\n
['Java']