【LeetCode】566. 重塑矩阵

566. 重塑矩阵(简单)

【LeetCode】566. 重塑矩阵_第1张图片
【LeetCode】566. 重塑矩阵_第2张图片

【LeetCode】566. 重塑矩阵_第3张图片【LeetCode】566. 重塑矩阵_第4张图片

方法:二维矩阵的一维表示

思路

【LeetCode】566. 重塑矩阵_第5张图片【LeetCode】566. 重塑矩阵_第6张图片

代码

class Solution {
public:
    vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {
        int m = mat.size(), n = mat[0].size();
        // 不合理的重塑方式 返回原矩阵
        if(m * n != r * c) return mat;

        vector<vector<int>> newMat(r, vector<int>(c, 0));
        for(int i = 0; i<m*n; ++i){
            newMat[i/c][i%c] = mat[i/n][i%n];
        }
        return newMat;
    }
};

你可能感兴趣的:(LeetCode刷题,leetcode,矩阵,算法)