5-liner C++ using global index


  • 0
        vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {
            int col = nums[0].size();
            if (nums.size()*col != r*c) return nums;
            
            vector<vector<int>> res(r, vector<int>(c));
            for (int i = 0; i < r*c; ++i) res[i/c][i%c] = nums[i/col][i%col];
            return res;
        }
    

Log in to reply
 

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