566. 重塑矩陣
在MATLAB
中,有一個非常有用的函數reshape
,它可以將一個m x n
矩陣重塑為另一個大小不同(r x c)
的新矩陣,但保留其原始數據。
給你一個由二維數組mat
表示的m x n
矩陣,以及兩個正整數r
和c
,分別表示想要的重構的矩陣的行數和列數。
重構后的矩陣需要將原始矩陣的所有元素以相同的行遍歷順序填充。
如果具有給定參數的reshape
操作是可行且合理的,則輸出新的重塑矩陣;否則,輸出原始矩陣。
示例 1:
輸入:mat = [[1,2],[3,4]], r = 1, c = 4
輸出:[[1,2,3,4]]
示例 2:
輸入:mat = [[1,2],[3,4]], r = 2, c = 4
輸出:[[1,2],[3,4]]
class Solution:
def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]:
tem = []
tem1 = []
for i in range(len(mat)):
for j in range(len(mat[i])):
tem.append(mat[i][j])
if r * c == len(tem):
for i in range(r):
tem2 = []
for j in range(c):
tem2.append(tem[0])
tem.pop(0)
tem1.append(tem2)
return tem1
else:
return mat
執行用時:136 ms, 在所有 Python3 提交中擊敗了5.24%的用戶
內存消耗:15.5 MB, 在所有 Python3 提交中擊敗了76.98%的用戶
這不是慢這是在打磨!在日本我可以當個仙人的!
- 根據題目要求,我們可以一開始先判斷轉換后矩陣的維度是否匹配轉換前矩陣的維度,如果不匹配則直接返回輸入矩陣即可
- 新建一個矩陣作為返回值
- 遍歷 r x c 個元素的同時找到兩個矩陣間對應的位置。這是一個簡單的除法問題:已知第i個元素,求在矩陣r行c列中的位置,即為i / c 行和 i % c 列。
class Solution:
def matrixReshape(self, nums, r, c):
row, col = len(nums), len(nums[0])
if row * col != r * c:
return nums
res = [[None] * c for _ in range(r)]
for i in range(r*c):
res[i//c][i%c] = nums[i//col][i%col]
return res
執行用時:28 ms, 在所有 Python3 提交中擊敗了96.82%的用戶
內存消耗:15.7 MB, 在所有 Python3 提交中擊敗了14.25%的用戶
118. 楊輝三角
給定一個非負整數 numRows
,生成「楊輝三角」的前 numRows
行。在「楊輝三角」中,每個數是它左上方和右上方的數的和。
**輸入: **numRows = 5
**輸出: **[[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]
class Solution:
def generate(self, numRows: int) -> List[List[int]]:
l = [[1]]
for i in range(1, numRows):
l.append([1])
for j in range(1, i):
l[i].append(l[i-1][j-1]+l[i-1][j])
l[i].append(1)
return l
執行用時:36 ms, 在所有 Python3 提交中擊敗了40.58%的用戶
內存消耗:15.1 MB, 在所有 Python3 提交中擊敗了13.05%的用戶
湊合用~