leetcode566. Reshape the Matrix

https://leetcode.com/problems/reshape-the-matrix/description/

public int[][] matrixReshape(int[][] nums, int r, int c) {
    int m = nums.length, n = nums[0].length;
    if (r * c != m * n)
        return nums;
    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;
}

序号对行数整除,取整是所在行数。对行数求余,是所在列数。

自己的代码: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[0].size())==r*c)
        {
           
             for(int i=0;i<r;i++)
            {
                for(int j=0;j<c;j++)
                {
                    cout<<nums[i][j]<<" ";
                    nums1[i][j]=nums[i][j];
                    
                }
               cout<<"
";
             }
          
            
        }
        else  
        {
            cout<<"the shape no match!"<<endl;
            for(int i=0;i<nums.size();i++)
            {
                for(int j=0;j<nums[i].size();j++)
                {
                    cout<<nums[i][j]<<" ";
                    nums1[i][j]=nums[i][j];
                    
                }
               cout<<"
";
            }
         
        
    }
        
        return nums1;
}};
原文地址:https://www.cnblogs.com/captain-dl/p/9706364.html