1170. Reshape the matrix

1170. Reshape the matrix

Chinese English

In MATLAB, there is a very useful function called 'reshape', which can reshape the matrix into a matrix of different size, but retain its original data.

First give a matrix represented by a two-dimensional array, and two positive integers r and c, respectively representing the number of rows and columns of the required reshaping matrix.

The reformed matrix needs to be filled with all the elements of the original matrix in the same row traversal order.

If the "reshape" operation using the given parameters is possible and legal, a new reshaping matrix is ​​output; otherwise, the original matrix is ​​output.

Sample

Example 1:

输入: 
nums = 
[[1,2],
 [3,4]]
r = 1, c = 4
输出: 
[[1,2,3,4]]
解释:
行遍历的顺序为 [1,2,3,4]. 新给出的矩阵大小为1 * 4, 根据前面给出的列表按行遍历即可。

Example 2:

输入: 
nums = 
[[1,2],
 [3,4]]
r = 2, c = 4
输出: 
[[1,2],
 [3,4]]
解释:
无法将一个2 * 2的矩阵整形称为一个2 * 4的矩阵。 所以输出原始矩阵。

Precautions

The size range of matrix rows and columns is [1, 100].
Both r and c are positive numbers.

Enter test data (one parameter per line) How to understand test data?
class Solution:
    """
    @param nums: List[List[int]]
    @param r: an integer
    @param c: an integer
    @return: return List [List [ int ]]
     "" "
     '' '
     General idea:
     1. First, initialize res = [], l = [], get the dimensions of nums, that is, len (nums) and len (nums [ 0 ]), and r * c to judge, if the product> = r * c, it means that the matrix can be reshaped, otherwise enter the original matrix.
     2. First stitch nums into a one-dimensional array, that is l = [...] The form,
     3. If you can reshape the matrix, according to the given r and c, loop l, giving current_dic = [], if the length is c, then append to res, until the length of res is r When break, finally return res
     ' ''
     def matrixReshape (self, nums, r, c):
        res = []
        current_dic = []
        l = []

        #If the conditions are not met
        if len(nums[0])*len(nums) < r*c:
            return  nums
        
        for i in nums:
            l.extend(i)

        #otherwise
        for column in l:
            current_dic.append(column)
            if len(current_dic) == c:
                res.append(current_dic)
                current_dic = []
            if len(res) == r:
                return res

 

 

Guess you like

Origin www.cnblogs.com/yunxintryyoubest/p/12685715.html