玩命加载中 . . .

566-重塑矩阵


LeetCode 566. Reshape the Matrix

LeetCode-566

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 row number and column number 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]]

method

给出二维下标[i,j]计算二维数组拉长的index,公式为
index = i * m + j
其中,m是二维数组的列数,可以看出iindex除以m的商,j是余数
所以,用一维index从二维数组中取值
matrix[index / m][index % m]

vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {
    int m = mat.size(), n = mat[0].size();
    if (r * c != m * n) return mat;
    vector<vector<int>> res(r, vector<int>(c));
    int idx = 0;
    for (int i = 0; i < r; ++i) {
        for (int j = 0; j < c; ++j) {
            res[i][j] = mat[idx / n][idx % n];
            idx++;
        }
    }
    return res;
}

文章作者: kunpeng
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 kunpeng !
  目录