当前位置:网站首页>566. Reshaping the matrix

566. Reshaping the matrix

2022-07-07 13:37:00 yitahutu79

stay MATLAB in , There's a very useful function reshape , It can put a m x n The matrix is remodeled to another different size (r x c) The new matrix of , But keep its original data .

Give you a two-dimensional array mat It means m x n matrix , And two positive integers r and c , Represent the number of rows and columns of the matrix to be reconstructed respectively .

The reconstructed matrix needs to replace all elements of the original matrix with the same Row traversal order fill .

If the reshape The operation is feasible and reasonable , The new reshaping matrix is output ; otherwise , Output raw matrix .

Example 1:

 Insert picture description here

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

Example 2:
 Insert picture description here

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

Tips :

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

class Solution {
    
public:
    vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {
    
        int m = mat.size();
        int n = mat[0].size();
        if (m * n  != r * c) {
    
            return mat;
        }
        vector<vector<int>> arr(r, vector<int>(c));
        for (int i = 0; i < m * n; i++) {
    
            arr[i/c][i%c] = mat[i/n][i%n];
        }
        return arr;
    }
};
原网站

版权声明
本文为[yitahutu79]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207071137441451.html