LeetCode #566. Reshape the Matrix

题目

566. Reshape the Matrix


解题方法

先判断能否reshape,如果可以再把原数组拆成一个一维数组,之后按照rc重新放置即可。
时间复杂度:O(r
c)
空间复杂度:O(r*c)


代码

class Solution:
    def matrixReshape(self, nums: List[List[int]], r: int, c: int) -> List[List[int]]:
        if len(nums[0]) * len(nums) != r * c:
            return nums
        
        numsarr = []
        for i in range(len(nums)):
            numsarr += nums[i]
        
        cur_pos = 0
        matrix = []
        for i in range(r):
            cur_row = []
            for j in range(c):
                cur_row.append(numsarr[cur_pos])
                cur_pos += 1
            matrix.append(cur_row)
        
        return matrix
posted @ 2020-11-03 09:44  老鼠司令  阅读(65)  评论(0)    收藏  举报