Leetcode 0566. Reshape the Matrix
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.
Description
In MATLAB, there is a handy function called reshape which can reshape
an m * n
matrix into a new one with a different size r * c
keeping its original data.
You are given an m * 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
Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
from typing import List
class Solution:
# Iteration
# Time Complexity: BigO(N^2)
# Space Complexity: BigO(N^2)
def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]:
if len(mat) * len(mat[0]) != r * c:
return mat
res = []
rowlist = []
for row in range(0, len(mat)):
for col in range(0, len(mat[row])):
rowlist.append(mat[row][col])
if len(rowlist) == c:
res.append(rowlist)
rowlist = []
return res
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/**
* Iteration
* Time Complexity: BigO(N^2)
* Space Complexity: BigO(N^2)
*/
function matrixReshape(mat: number[][], r: number, c: number): number[][] {
if (r * c != mat.length * mat[0].length) return mat;
let res: number[][] = [];
let rowList: number[] = [];
let row = 0;
let col = 0;
while (
res.reduce((acc, cur) => (acc += cur.length), 0) <
mat.length * mat[0].length
) {
if (typeof mat?.[row]?.[col] === "undefined") {
row += 1;
col = 0;
}
rowList.push(mat?.[row]?.[col]);
if (rowList.length == c) {
res.push(rowList);
rowList = [];
}
col += 1;
}
return res;
}
This post is licensed under CC BY 4.0 by the author.