In MATLAB, there are a very useful function called ' reshape ', which can reshape a matrix into a new one with different size But keep its original data.
You ' re given a matrix represented by a two-dimensional array, and the positive integers r and C representing the row Numbe R and column number of the wanted reshaped matrix, respectively.
The reshaped matrix need to is filled with all the elements of the original matrix in the same row-traversing order as the Y were.
If the ' reshape ' operation with given parameters are possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.
Example 1:
Input:
Nums =
[[+],
[3,4]]
R = 1, c = 4
Output:
[[1,2,3,4]]
Explanation:
The row-traversing of Nums is [1,2,3,4]. The new reshaped matrix is a 1 * 4 matrix, and the fill it row by row by using the previous list.
Example 2:
Input:
Nums =
[[+],
[3,4]]
R = 2, c = 4
Output:
[[+],
[3,4]]
Explanation:
There is no-to-reshape a 2 * 2 matrix to a 2 * 4 matrix. So output the original matrix.
Note:
The height and width of the given matrix is in range [1, 100].
The given R and C is all positive.
The requirements described in this question are:
We need to refactor a matrix.
Provide us with a matrix, and then give us two integers r and C that want us to re-form the matrix of the R row C column
If you cannot refactor back to the original determinant
Thought is:
The first thing to judge is that if R*c equals the number of elements in a given matrix, it can be reconstructed
Refactoring takes all the elements out and generates a new matrix as required.
My Python code:
1 classsolution (object):2 defMatrixreshape (self, nums, R, c):3 """4 : Type Nums:list[list[int]]5 : Type R:int6 : Type C:int7 : Rtype:list[list[int]]8 """9 ifR*c = = Len (nums) *Len (nums[0]):TenNewList = [i forJinchRange (len (nums)) forIinchNums[j]] One return[[Newlist.pop (0) forIinchRange (c)] forJinchRange (r)] A Else: - returnNums - the - - if __name__=='__main__': -s =solution () +res = S.matrixreshape ([[1,2],[3,4]],1,4) - #res = S.matrixreshape ([[1, 2], [3, 4]],4,1) + Print(RES)
Leetcode algorithm: Reshape the Matrix