Simple python solution with detailed explaination

  • 0

    The key point of this problem is to check whether the number of original matrix equals to the reshape target, that is n=r multiply c, n means the total number of the original matrix.
    Step1, check the 'n==r multiply c', if not, the original numbers could not fill in the new matrix, and then return the original one
    Step2, creat target reshape matrix by filling zeros, or other numbers you like :) , anyway, they'll finally be substituded by the numbers from nums
    Step3, store the traversal numbers from original list in a one dimension array
    Step4, fill in the reshape matrix with the traversal array.

        def matrixReshape(self, nums, r, c):
            :type nums: List[List[int]]
            :type r: int
            :type c: int
            :rtype: List[List[int]]
            if nums==[]:return []
            if r*c!=len(nums)*len(nums[0]):return nums
            matrix=[[0 for col in range(c)] for row in range(r)]
            for i in range(len(nums)):
                for j in range(len(nums[0])):
            for i in range(r):
                for j in range(c):
            return matrix

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.