Extra space to store original matrix


  • 0
    class Solution {
    public:
        vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {
            int m = nums.size(), n = nums[0].size();
            if (m * n != r * c) {
                return nums;
            }
    
            // Use extra space to convert orginal vector into 1-dimension 
            vector<int> vecTmp;
            for (int i = 0; i < m; i++) {
                for (int j = 0; j < n; j++) {
                    vecTmp.push_back(nums[i][j]);
                }
            }
            
            // In the end, index == r * c
            int index = 0;
            vector<vector<int>> res(r, vector<int>(c, 0));
            for (int i = 0; i < r; i++) {
                for (int j = 0; j < c; j++) {
                    res[i][j] = vecTmp[index++];
                }
            }
    
            return res;
        }
    };
    

Log in to reply
 

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