Steward
分享是一種喜悅、更是一種幸福
程式語言 - LeetCode - C++ - 566. Reshape the Matrix
題目:

解答:
class Solution {
public:
vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {
int pos = 0;
int m = mat.size();
int n = mat[0].size();
vector<vector<int>> ans;
vector<int> t;
if (m *n != r * c) {
r = min(r, m);
c = (m * n) / r;
}
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
t.push_back(mat[i][j]);
pos += 1;
if (pos >= c) {
ans.push_back(t);
t.clear();
pos = 0;
}
}
}
return ans;
}
};