Python solution with comments


  • 1
    class Solution(object):
        def matrixReshape(self, nums, r, c):
            """
            :type nums: List[List[int]]
            :type r: int
            :type c: int
            :rtype: List[List[int]]
            """
            
            # check if nums is empty
            if not nums :
                return nums
                
            # calculate h(height) and w(width) of nums
            h = len(nums)
            w = len(nums[0])
            
            # check if the reshape operation is valid
            if h*w != r*c :
                return nums
                
            # build reshaped list
            res = [[0]*c for _ in xrange(r)] 
            
            # do reshape
            for i in xrange(h*w):
                    res[i/c][i%c] = nums[i/w][i%w]
            return res
    

Log in to reply
 

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