JavaScript Functional Solution with 2 reduces


  • 0
    /**
     * @param {number[][]} nums
     * @param {number} r
     * @param {number} c
     * @return {number[][]}
     */
    var matrixReshape = function(nums, r, c) {
        if(nums[0].length * nums.length !== r*c){
            return nums;
        }
    
        var order = nums.reduce(function(acc,item){
            return acc.concat(item);
        }, [])
        
        var newMatrix =[];    
        order.reduce(function(accumulator, value, idx){
            if(idx === c-1 || (idx+1) % c === 0){
                accumulator.push(value);
                newMatrix.push(accumulator);
                accumulator = [];
            } else {
                accumulator.push(value);
            }
            return accumulator;
        },[]);
        
        return newMatrix;
    };
    

Log in to reply
 

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