566. Reshape the Matrix

problem

solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {
vector<vector<int>> ret(r, vector<int>(c,0));
if(r*c!=mat.size()*mat[0].size()) return mat;
int k =0, n = mat[0].size();
for(int i=0;i<r;i++){
for(int j = 0;j<c;++j){
k = i*c+j;
ret[i][j] = mat[k/n][k%n];
}
}
return ret;
}
};
  • easy understand
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    class Solution {
    public:
    vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {
    int n = mat.size(), m = mat[0].size();
    if(n*m != r*c) return mat;
    vector<vector<int>> ret(r, vector<int>(c,0));
    int k =0;
    for(int i=0;i<r;++i){
    for(int j=0;j<c;++j){
    ret[i][j] = mat[k/m][k%m];
    k++;
    }
    }
    return ret;
    }
    };

    analysis

  • time complexity O(n)
  • space complexity O(1)