LeetCode:(Python)(Array)Reshape the Matrix

許博淳
數據共筆
Published in
4 min readMar 19, 2023

題目連結:https://leetcode.com/problems/reshape-the-matrix/description/

題意說明:

  • 給定一個 matrix,以及行數和列數,按照行數和列數排列
  • 如果無法按照行數和列數排列,傳回最原始的 matrix

初始想法

  • 將 mat結合成一維 list
  • 如果行數和列數無法達成就回傳原始 mat
  • 如果條件可達成,用迴圈切割一維 list

實作程式碼

class Solution:
def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]:
#壓成一維 list
merge = []
for m in mat:
merge += m
#條件不能達成就回傳
if r*c != len(merge):
return mat
#用迴圈切割
output = []
for i in range(0,len(merge),c):
output.append(merge[i:i+c])
return output

表現不錯

嘗試拿掉一個 for loop

實作程式碼

class Solution:
def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]:
merge = sum(mat,[])

if r*c != len(merge):
return mat

output = []
for i in range(0,len(merge),c):
output.append(merge[i:i+c])
return output

實務上表現和第一種解法差不多

參考他人解法

解法連結:https://leetcode.com/problems/reshape-the-matrix/solutions/2530159/2-easy-peasy-python-solutions-faster-than-98-37/?orderBy=hot&languageTags=python

  • 我原本的作法是降維再建構解答
  • 這個解法直接在二維結構組成答案

實作程式碼

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

output = []
temp = []
#逐行逐列走
for i in range(len(mat)):
for j in range(len(mat[0])):
temp.append(mat[i][j])
#當 list達到每列上限就輸出,然後清空
if len(temp) == c:
output.append(temp)
temp = []

return output

實務上表現非常好

--

--