其他分享
首页 > 其他分享> > 566. 重塑矩阵

566. 重塑矩阵

作者:互联网

class Solution {
public:
    vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) 
    {
        vector<vector<int>> ans(r,vector<int>(c,0));
        int m = nums.size();
        int n = nums[0].size();

        if(r*c > m*n)
        {
            return nums;
        }

        int nR = 0;
        int nC = 0;
        for (int i = 0; i < m; ++i) 
        {
            for (int j = 0; j < n; ++j) 
            {
                ans[nR][nC] = nums[i][j];
                nC++;
                if (nC == c) 
                {
                    nR += 1;
                    nC = 0;
                }
            }
        }
        return ans;
    }
};
class Solution {
public:
    vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {
        int m = nums.size();
        int n = nums[0].size();
        if (m * n != r * c) {
            return nums;
        }

        vector<vector<int>> ans(r, vector<int>(c));
        for (int x = 0; x < m * n; ++x) {
            ans[x / c][x % c] = nums[x / n][x % n];
        }
        return ans;
    }
};

 

标签:return,nums,int,nC,矩阵,566,vector,重塑,ans
来源: https://blog.csdn.net/qq_41078889/article/details/113831181