1. Topics
In Matlab, there is a very useful function reshape
that can reshape a matrix to another new matrix of different sizes, but retains its original data.
gives a matrix represented by a two-dimensional array, and two positive integers r
c
, respectively, representing the number of rows and columns of the matrix you want to refactor.
The reconstructed matrix requires that all elements of the original matrix be populated in the same row traversal order .
If the operation with the given parameters reshape
is feasible and reasonable, the new reshaping matrix is output; otherwise, the original matrix is output.
Example 1:
input: nums = [[], [3,4]]r = 1, c = 4 output: [[[1,2,3,4]] explanation: The result of the row traversal nums is [1,2,3,4]. The new matrix is a 1 * 4 matrix that fills the new matrix with a row of previous element values.
Example 2:
input: nums = [[], [3,4]]r = 2, c = 4 output: [[], [3,4]] explanation: There is no way to convert the 2 * 2 matrix into a 2 * 4 matrix. So output the original matrix.
Attention:
- The width and height range of a given matrix is in [1, 100].
- The given R and C are positive numbers.
2. Ideas
First convert the original matrix into an iterator, all the numbers are put in, "can also be put into the queue", and then create a new matrix (size of reshape size), one to the inside of the number.
Converting a list into an iterator can be chain.from_iterable (list) functions under the Itertools module . Then use the next function to take a number
One more point: one way to create a two-dimensional matrix:
For i in range (r):
Result.append ([])
For J in Range (c):
Result[i].append (Next (Chainnum))
Second type: result = [[] * R for I in Range (c)] "List Builder"
3. Code
fromItertoolsImportchainclasssolution (object):defMatrixreshape (self, nums, R, c):""": Type Nums:list[list[int]]: Type R:int:type c:int:rtype:list[list[int]] """ if notNums:returnNumselif notRor notC:returnNumsElse: H=Len (nums) L=Len (nums[0])ifH*l! = r*C:returnNumsElse: Chainnum=chain.from_iterable (nums) result= [] forIinchRange (R): Result.append ([]) forJinchRange (c): Result[i].append (Next (chainnum))returnResult
Algorithm----Reshape matrix LeetCode566