LeetCode 筆記 - 566. Reshape the Matrix

題目在此 566. Reshape the Matrix

實作出 MATLAB 裡面的 reshape 函式
給定一個 matrix 與新的長寬 r, c

我們要做的事情就是將 matrix 資料擺放成 r, c 的形狀

image 53

解題思維

…這題要怎麼解釋(思考)
就…擺啊?

唯一需要比較注意的地方是,如果給定的 r, c 不合理,就不做事

完成 🥰

程式碼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution:
def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]:

result = []

size_y = len(mat)
size_x = len(mat[0])

if size_y * size_x != r * c:
return mat

index = 0

result = []
current_result = []
for m in mat:
for v in m:
current_result.append(v)

index += 1
if index % c == 0:
result.append(current_result)
current_result = []

return result

相關文章