Leetcode # 566. Reshape the Matrix

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

Solution

Time Complexity: O(r * c)
Space Complexity: O(1)
(The input and output generally do not count towards the space complexity.)

new_mat = [[0 for j in range(c)] for i in range(r)]
 new_mat = [[0] * c] * r

 

class Solution:
  def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]:
    if r * c != len(mat) * len(mat[0]):
      return mat
    new_mat = [[0 for j in range(c)] for i in range(r)]
    i = j = 0
    for row in mat:
      for e in row:
        print(i, j, e)
        new_mat[i][j] = e
        j = (j + 1) % c
        i = (i + 1) if j == 0 else i
    return new_mat

 

Last Updated on 2023/08/16 by A1go

目錄

目錄
Bitnami