码迷,mamicode.com
首页 > 其他好文 > 详细

566. Reshape the Matrix

时间:2020-07-01 20:44:58      阅读:69      评论:0      收藏:0      [点我收藏+]

标签:list   lis   ber   column   new   original   返回   function   UNC   

In MATLAB, there is 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 two positive integers r and c representing the row number and column number of the wanted reshaped matrix, respectively.

The reshaped matrix need to 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.

把矩阵reshape成r行c列的。如果原本的n*m不等于r*c的话就返回原矩阵

class Solution(object):
    def matrixReshape(self, nums, r, c):
        """
        :type nums: List[List[int]]
        :type r: int
        :type c: int
        :rtype: List[List[int]]
        """
        n = len(nums)
        m = len(nums[0])
        if n * m != r * c:
            return nums
        row = 0
        col = 0
        ans = []
        for i in range(r):
            ans.append([0] * c)
        for i in range(n):
            for j in range(m):
                ans[row][col] = nums[i][j]
                col += 1
                if col == c:
                    col = 0
                    row += 1
        return ans
        

 

566. Reshape the Matrix

标签:list   lis   ber   column   new   original   返回   function   UNC   

原文地址:https://www.cnblogs.com/whatyouthink/p/13220892.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!