leetcode 566. 重塑矩阵
class Solution: def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]: m,n = len(mat),len(mat[0]) if m * n != r * c: return mat ans = [[0] * c for _ in range(r)] for i in range(m*n): ans[i//c][i%c] = mat[i//n][i%n] return ans
len(mat),len(mat[0])两个 *** 作跟c++中的求二位数组的列数和行数有点像,m*n的矩阵映射成一维矩阵,在从一维矩阵转成 r*c 的矩阵,具体看官方题解,flatten *** 作不香嘛...
leetcode 118. 杨辉三角
class Solution: def generate(self, numRows: int) -> List[List[int]]: ans = [[1]] while len(ans) < numRows: ls = [a+b for a,b in zip([0]+ans[-1],ans[-1]+[0])] ans.append(ls) return ans
有大佬找到规律,每一行等于前一行错位相加。直接照着大佬思路,分别在前一行首尾加上一个[0],两个等长的数组错位相加,将得到的这一行数组加入列表
leetcode告诉我,我是个废物,道阻且长。写数据结构的题思路有时候都没有
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)