Skip to content

Latest commit

 

History

History
27 lines (25 loc) · 694 Bytes

566.md

File metadata and controls

27 lines (25 loc) · 694 Bytes

566. Reshape the Matrix

Solution 1 (time O(mn), space O(1))

class Solution(object):
    def matrixReshape(self, mat, r, c):
        """
        :type mat: List[List[int]]
        :type r: int
        :type c: int
        :rtype: List[List[int]]
        """
        m, n = len(mat), len(mat[0])
        if m * n != r * c:
            return mat
        ans = [[0 for _ in range(c)] for _ in range(r)]
        p1, p2 = 0, 0
        for i in range(m):
            for j in range(n):
                ans[p1][p2] = mat[i][j]
                p2 += 1
                if p2 == c:
                    p1 += 1
                    p2 = 0
        return ans