#566. Reshape the Matrix

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

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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容