https://leetcode.com/problems/reshape-the-matrix/description/
public int[][] matrixReshape(int[][] nums, int r, int c) {
int m = nums.length, n = nums[].length;
if (r * c != m * n)
return nums;
int[][] reshaped = new int[r][c];
for (int i = ; i < r * c; i++)
reshaped[i/c][i%c] = nums[i/n][i%n]; %核心公式
return reshaped;
}
序号对行数整除,取整是所在行数。对行数求余,是所在列数。
自己的代码:1.不够简洁 ,有点累赘 2.compiler error,找不出原因,哈哈哈哈
class Solution {
public:
vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {
vector<vector<int>> nums1(r,vector<int>(c));
if((nums.size()*nums[].size())==r*c)
{ for(int i=;i<r;i++)
{
for(int j=;j<c;j++)
{
cout<<nums[i][j]<<" ";
nums1[i][j]=nums[i][j]; }
cout<<"\n";
} }
else
{
cout<<"the shape no match!"<<endl;
for(int i=;i<nums.size();i++)
{
for(int j=;j<nums[i].size();j++)
{
cout<<nums[i][j]<<" ";
nums1[i][j]=nums[i][j]; }
cout<<"\n";
} } return nums1;
}};