Python solution

  • 3

    I know that the code looks ugly, but it is good enough for a beginner like me :)

    class Solution(object):
        def matrixReshape(self, nums, r, c):
            :type nums: List[List[int]]
            :type r: int
            :type c: int
            :rtype: List[List[int]]
            nrows = len(nums)
            ncols = len(nums[0])
            if nrows * ncols == r * c:
                onedArray = []
                reshaped = [[0] * c for i in range(r)]
                for x in nums:
                    onedArray += x
                for index, item in enumerate(onedArray):
                    placeRow = index / c
                    placeCol = index % c
                    reshaped[placeRow][placeCol] = item
                return reshaped
                return nums

Log in to reply

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