2023年8月2日 星期三

8/1 每日一題(PY 將矩陣轉換成新的的r*c矩陣)

 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.

 

Example 1:

Input: mat = [[1,2],[3,4]], r = 1, c = 4
Output: [[1,2,3,4]]

Example 2:

Input: mat = [[1,2],[3,4]], r = 2, c = 4
Output: [[1,2],[3,4]]

 

Constraints:

  • m == mat.length
  • n == mat[i].length
  • 1 <= m, n <= 100
  • -1000 <= mat[i][j] <= 1000
  • 1 <= r, c <= 300







class Solution:
    def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]:
        raw=len(mat) #列
        col=len(mat[0])  #行      
        arr=[] #初始化記錄用元素
        if raw*col != r*c:
            return mat  #無法轉換
        if raw == r: #相同
            return mat
        res=[[0]*c for i in range(r)]  #初始化二維陣列

        for i in mat:
            for j in i:
                arr.append(j)
        n=0
        for i in range(r):
            for j in range(c):
                res[i][j]=arr[n]
                n+=1
        return res





----------------參考答案

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

        final = []
        temp = 0
        c_temp = 0
        row = []

        for i in range(len(mat)):
            for j in range(len(mat[0])):
                if c_temp == c:
                    final.append(list(row))
                    row.clear()
                    c_temp = 0

                row.append(mat[i][j])
                c_temp += 1
        if row:
            final.append(list(row))
        return final
        
























標籤:

0 個意見:

張貼留言

訂閱 張貼留言 [Atom]

<< 首頁