JavaScript one loop solution


  • 0

    Let's take an example to explain

    input : [[1,2,3], [4,5,6], [7,8,9], [10,11,12]]
    r:4 c:3

    First we will reduce the input to [1,2,3,4,5,6,7,8,9,10,11,12]
    Next, we run the loop 4(r) times, each time we push 3(c) elements into the result array

    That's all

    var matrixReshape = function(nums, r, c) {
        let total = 0;
        // First we reduce the array to an one-dimensional array
        let data = nums.reduce(collecter);
    
        if (data.length < r * c) {
            return nums;
        }
        
        let result = []
        let start = 0;
        // For r rows, slice c elements into the result array
        // btw you can also use splice but it will change the original array
        for (let i = 0; i< r; i++) {
            result.push(data.slice(start, start + c));
            start += c;
        }
    
        return result;
    };
    
    var collecter = function (acc, val) {
        return acc.concat(val);  
    };
    

Log in to reply
 

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