您的位置:首页 > 其它

566. Reshape the Matrix

2018-01-20 21:27 260 查看

题目描述:

In MATLAB, there is a very useful function called ‘reshape’, which can reshape a matrix into a new one with different size but keep its original data.

You’re given a matrix represented by a two-dimensional array, and two positive integers r and c representing the row number and column number of the wanted reshaped matrix, respectively.

The reshaped matrix need to 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.

解题思路:

这道题很简单,就是检查二维数组能否把两个维度大小改变一下仍能存下相同数量的元素。

代码如下:

//注意一下嵌套vector的初始化即可
class Solution {
public:
vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {
if (nums.size() * nums[0].size() == r * c) {
vector<vector<int>> temp(r);
for (int i = 0; i < r; ++i)
temp[i].resize(c);
for (int i = 0; i < r * c; ++i) {
//通过求商和求余的方式来简化代码。
temp[i / c][i % c] = nums[i / nums[0].size()][i % nums[0].size()];
}
return temp;
}
else {
return nums;
}
}
};


//嵌套vector可以不初始化,但是应该不可以在用之前用下标给赋值了。
class Solution {
public:
vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {
if (nums.size() * nums[0].size() == r * c) {
vector< vector <int> > temp;
vector<int> temp2;
for (int i = 0; i < nums.size(); ++i) {
for (int j = 0; j < nums[0].size(); ++j) {
if (temp2.size() < c)
temp2.push_back(nums[i][j]);
else {
//push整个vector<int>
temp.push_back(temp2);
temp2.clear();
temp2.push_back(nums[i][j]);
}
}
}
//push整个vector<int>
temp.push_back(temp2);
return temp;
}
else {
return nums;
}
}
};


//注意一下二维数组动态申请内存的方法
public int[][] matrixReshape(int[][] nums, int r, int c) {
int m = nums.length, n = nums[0].length;
if (r * c != m * n)
return nums;
//动态分配,r和c都是变量
int[][] reshaped = new int[r][c];
for (int i = 0; i < r * c; i++)
reshaped[i/c][i%c] = nums[i/n][i%n];
return reshaped;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: