C++ solution (39ms)


  • 0
    K
    class Solution {
    public:
        vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {
            int old_c = nums[0].size();
            int old_r = nums.size();
            
            if (old_c * old_r != r * c)
                return nums;
    
            vector<vector<int>> reshaped(r, vector<int>(c));
            int old_i = 0; // row
            int old_j = 0; // col
            for (int i = 0; i < r; ++i) // row
            {
                for (int j = 0; j < c; ++j) // col
                {
                    reshaped[i][j] = nums[old_i][old_j++];
                    if (old_j == old_c)
                    {
                        old_j = 0;
                        ++old_i;
                    }
                }
            }
            return reshaped;
        }
    };
    

Log in to reply
 

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