566. Reshape the Matrix

原题地址:https://leetcode.com/problems/reshape-the-matrix/description/
大意:重塑一个二维矩阵,例如将14的变为22的,86的编程412的。不难发现,必须重塑之前的元素和之后的元素个数相等才行。

class Solution:
    def matrixReshape(self, nums, r, c):
        """
        :type nums: List[List[int]]
        :type r: int
        :type c: int
        :rtype: List[List[int]]
        """
        len_1 = len(nums) * len(nums[0])
        len_2 = r * c
        list = []
        if len_1 != len_2:
            return nums
        else:
            for row in nums:
                for col in row:
                    list.append(col)
            newMatrix = [[0 for x in range(c)] for y in range(r)]
            for i in range(r):
                for j in range(c):
                    newMatrix[i][j] = list[i*c+j]
            return newMatrix


a = Solution()
print (a.matrixReshape([[1,2],[3,4]],r = 1, c = 4))

知识点:

  • 怎么样新建一个二维矩阵
    Matrix = [][]或者Matrix = [5][5]都是不行的
#Creates a list containing 5 lists, each of 8 items, all set to 0
w, h = 8, 5;
Matrix = [[0 for x in range(w)] for y in range(h)] 




所有题目解题方法和答案代码地址:https://github.com/fredfeng0326/LeetCode

你可能感兴趣的:(566. Reshape the Matrix)