Intuitive Javascript Solution


  • 0
    D
    var matrixReshape = function(nums, r, c) {
        const numsRow = nums.length;
        const numsCol = nums[0].length;
        const output = [];
        
        let flatNums = null;
        
        // return original if new dimension doesn't match 
        if (r * c !== numsRow * numsCol) return nums;
        
        // deconstruct the original array and reconstruct new array
        flatNums = nums.reduce((acc, curr) => acc.concat(curr), []);
        
        for (let i = 0; i < r; i++) 
            output.push(flatNums.splice(0, c));
        
        return output;
    };
    

Log in to reply
 

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