39ms simple C++ solution


  • 1
    L
    class Solution {
    public:
        vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {
            int area=nums.size()*nums[0].size();
            if(area!=r*c) return nums;
            vector<vector<int> > res(r);
            int i=0,j=0;
            int rows=nums.size(),cols=nums[0].size();
            for(int m=0;m<rows;++m)
            {
               for(int n=0;n<cols;++n)
                {
                    res[i].push_back(nums[m][n]);
                    if((++j)%c==0) ++i;
                }
            }
            return res;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.