Javascript simple solution(use queue)


  • 0
    M
    var matrixReshape = function(nums, r, c) {
        var queue = [];
        var i, j, result = [];
    
        // create a queue from nums
        for (i = 0; i < nums.length; i++) {
            queue = queue.concat(nums[i]);
        }
        
        // The reshaped matrix need to be filled with ALL the elements
        // so if r*c not equal to queue.length, it means new matrix cannot be formed, return original arr
        if (queue.length !== r * c) {
            return nums;
        }
    
        for (i = 0; i < r; i++) {
            result[i] = [];
            for (j = 0; j < c; j++) {
                result[i].push(queue.shift());
                // result[i][j] = queue.shift();   // no speed diff
            }
        }
    
        return result;
    };
    

Log in to reply
 

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