Simple Python solution

  • 1

    This solution loops through all of the values in the nums array and appends it to a temp array. Once that temp array has the length of c, it appends that to another array I call, "result."

    I reset the count for c to 0 and I continue doing this until all of the values are recreated in the "result" array.

    There's also a conditional to check if the areas match for both the current and reshaped array.

    I haven't looked at other solutions yet and this is my first attempt.

    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 (r * c) != len(nums) * len(nums[0]):
                return nums
            result = []
            temp = []
            count = 0
            for i in range(len(nums)):
                for j in range(len(nums[0])):
                    # create an array with length of c
                    count += 1
                    if count == c:
                        # append the array to the result array
                        # this makes sure it has the new c length 
                        temp = []
                        count = 0
            return result

Log in to reply

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