0
点赞
收藏
分享

微信扫一扫

Leetcode self-record [day 4]

胡桑_b06e 2022-02-18 阅读 76
python

[Data Structure Study Plan] - Day 4

566. Reshape the Matrix

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.

Solution:

class Solution:
    def matrixReshape(self, mat, r, c):
        l, w = len(mat), len(mat[0])
        if l * w != r * c: return mat
        result = [[0] * c for _ in range(r)]
        for i in range(l * w):
            result[i // c][i % c] = mat[i // w][i % w]
        return result

Remark:

r * c = m * n simplifies filtering unchanged matrix.

result[i // c][i % c] = mat[i // w][i % w] gives us col number first, row number next, which is a natural reading sequence of matrix.

Feedback:

Runtime: 103 ms, faster than 60.85% of Python3 online submissions for Reshape the Matrix.

Memory Usage: 14.8 MB, less than 74.20% of Python3 online submissions for Reshape the Matrix.


118. Pascal's Triangle

Given an integer numRows, return the first numRows of Pascal's triangle.

In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:...

Solution:

class Solution:
    def generate(self, numRows):
        antwolt = list([1]*i for i in range(1, numRows+1))
        for i in range(numRows):
            for j in range(1, i):
                antwolt[i][j] = antwolt[i-1][j-1] + antwolt[i-1][j]
        return antwolt

Remark:

The idea is to formulate the answer first, then update it with requirements.

Feedback:

Runtime: 35 ms, faster than 61.26% of Python3 online submissions for Pascal's Triangle.

Memory Usage: 13.9 MB, less than 74.35% of Python3 online submissions for Pascal's Triangle.

To be continued... : )

举报

相关推荐

0 条评论