LeetCode 566: Reshape the Matrix

Problem Description

Explanation

To reshape the matrix, we need to iterate through the original matrix row by row and fill the elements into a new matrix with the desired number of rows and columns. We can achieve this by using two nested loops. First, we check if the reshape operation is possible by checking if the total number of elements in the original matrix equals the total number of elements in the reshaped matrix. If it is possible, we iterate through the original matrix, keeping track of the current position in the reshaped matrix.

  • Time complexity: O(m * n) where m is the number of rows and n is the number of columns in the original matrix.
  • Space complexity: O(r * c) where r is the number of rows and c is the number of columns in the reshaped matrix.

Solutions

class Solution {
    public int[][] matrixReshape(int[][] mat, int r, int c) {
        int m = mat.length;
        int n = mat[0].length;

        if (m * n != r * c) {
            return mat;
        }

        int[][] reshaped = new int[r][c];
        int row = 0, col = 0;

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                reshaped[row][col] = mat[i][j];
                col++;
                if (col == c) {
                    row++;
                    col = 0;
                }
            }
        }

        return reshaped;
    }
}

Loading editor...