#566. Reshape the Matrix

https://leetcode.com/problems/reshape-the-matrix/#/hints

#566. Reshape the Matrix_第1张图片
image.png

思路

  • 关键就是原矩阵和reshape后的矩阵元素的对应关系
  • mat第k个元素为 i * 列 + j 即mat[i][j]
  • i = k // 列 , j = k % 列
  • k = i * reshape_col + j
  • reshape[i][j] = nums[k // nums_col][k % nums_col]

Python

class Solution(object):
    def matrixReshape(self, nums, r, c):
        """
        :type nums: List[List[int]]
        :type r: int
        :type c: int
        :rtype: List[List[int]]
        """
        rr = len(nums)
        cc = len(nums[0])
        if rr * cc != r * c:
            return nums
        nums_new = []
        for i in range(r):
            tmp = []
            for j in range(c):
                k = i * c + j
                tmp.append(nums[k // cc][k % cc])
            nums_new.append(tmp)
        return nums_new

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