문제
In MATLAB, there is a handy function called reshape which can reshape an m x n matrix into a new one with a different size r x c keeping its original data.
You are given an m x n matrix mat and two integers r and c representing the number of rows and the number of columns of the wanted reshaped matrix.
The reshaped matrix should be filled with all the elements of the original matrix in the same row-traversing order as they were.
If the reshape operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.
코드
class Solution(object):
def matrixReshape(self, mat, r, c):
answer = sum(mat, [])
arr = []
if len(answer) == r * c:
for i in range(0,len(answer),c):
num = answer[i:i+c]
arr.append(num)
return arr
else:
return mat
분석 > 이 문제는 어렵지 않았지만 2차원 배열을 1차원 배열로 바꾸는 법을 새롭게 알게 되었던 문제이다. sum(배열, []) 을 꼭 기억해 두자.
'Algorithm > Leetcode' 카테고리의 다른 글
[Leetcode] Clumsy Factorial (#1006) (0) | 2022.04.21 |
---|---|
[Leetcode] Print Words Vertically (#1324) (0) | 2022.04.20 |
[Leetcode] Complex Number Multiplication (#537) (0) | 2022.04.20 |
[Leetcode] Game of Life (#289) (0) | 2022.04.19 |
[Leetcode] Transpose Matrix (#867) (0) | 2022.04.18 |