LeetCode 0566. Reshape the Matrix Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
0566. Reshape the Matrix

Description

In MATLAB, there is a handy function called reshape which can reshape an m x n matrix into a new one with a different size r x c keeping its original data.

You are given an m x n matrix mat and two integers r and c representing the number of rows and the number of columns of the wanted reshaped matrix.

The reshaped matrix should be filled with all the elements of the original matrix in the same row-traversing order as they were.

If the reshape operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.

 

Example 1:

Input: mat = [[1,2],[3,4]], r = 1, c = 4
Output: [[1,2,3,4]]

Example 2:

Input: mat = [[1,2],[3,4]], r = 2, c = 4
Output: [[1,2],[3,4]]

 

Constraints:

  • m == mat.length
  • n == mat[i].length
  • 1 <= m, n <= 100
  • -1000 <= mat[i][j] <= 1000
  • 1 <= r, c <= 300

Solutions

Solution 1: Simulation

First, we get the number of rows and columns of the original matrix, denoted as m and n respectively. If m × n ≠ r × c, then the matrix cannot be reshaped, and we return the original matrix directly.

Otherwise, we create a new matrix with r rows and c columns. Starting from the first element of the original matrix, we traverse all elements in row-major order and place the traversed elements into the new matrix in order.

After traversing all elements of the original matrix, we get the answer.

The time complexity is O(m × n), where m and n are the number of rows and columns of the original matrix, respectively. Ignoring the space consumption of the answer, the space complexity is O(1).

PythonJavaC++GoTypeScriptRustC
class Solution: def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]: m, n = len(mat), len(mat[0]) if m * n != r * c: return mat ans = [[0] * c for _ in range(r)] for i in range(m * n): ans[i // c][i % c] = mat[i // n][i % n] return ans(code-box)

Solution 2

TypeScript
function matrixReshape(mat: number[][], r: number, c: number): number[][] { const m = mat.length; const n = mat[0].length; if (m * n !== r * c) { return mat; } const ans = Array.from({ length: r }, () => new Array(c).fill(0)); for (let i = 0; i < r * c; i++) { ans[Math.floor(i / c)][i % c] = mat[Math.floor(i / n)][i % n]; } return ans; }(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !