My solution - two approaches


  • 0
    S
    class Solution(object):
        def matrixReshape(self, nums, r, c):
            """
            :type nums: List[List[int]]
            :type r: int
            :type c: int
            :rtype: List[List[int]]
            """
            if nums:
                m = len(nums)
                n = len(nums[0])
                if m*n != r*c:
                    return nums
                
                new = [ [ 0 for j in range(c) ] for i in range(r) ]
                
                for i in range(m):
                    for j in range(n):
                        offset = i*n + j # number of rows * number of items per row + offset into row
                        new[offset // c ][ offset%c ] = nums[i][j]
                return new
    
                """
                alternate approach with temp array
                t = []
                for i in range(m):
                    for j in range(n):
                        t.append(nums[i][j])
                
                new = [ [ 0 for i in range(c)] for j in range(r) ]
                k = 0
                for i in range(r):
                    for j in range(c):
                        new[i][j] = t[k]
                        k += 1
                return new
                """
                
            return nums

Log in to reply
 

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