C++ Simple Solution, Concise Code


  • 0
    class Solution {
    public:
        vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {
            int m = nums.size(), n = m ? nums[0].size() : 0;
            if (m * n != r * c)
                return nums;
            vector<vector<int>> ret(r, vector<int>(c));
            int cnt = 0;
            for (int i = 0; i < m; i++) {
                for (int j = 0; j < n; j++) {
                    ret[cnt / c][cnt % c] = nums[i][j];
                    cnt++;
                }
            }
            return ret;
        }
    };
    

Log in to reply
 

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