JavaScript O(rc) solution


  • 0
    var matrixReshape = function(nums, r, c) {
        if (nums.length * nums[0].length !== r * c) return nums;
        const res = [];
        for (let rn = 0; rn < nums.length; rn++) {
            for (let cn = 0; cn < nums[0].length; cn++) {
                let i = rn * nums[0].length + cn;
                let rr = Math.floor(i / c);
                let cr = i % c;
                res[rr] = [...res[rr] || [], nums[rn][cn]];
            }
        }
        return res;
    };
    

    The spread operator isn't too snappy, so you could also do:

    if (!res[rr]) res.push([]);
    res[rr].push(nums[rn][cn]);
    

    And here's an ugly two-liner for fun:

    var matrixReshape = function(nums, r, c) {
        const all = nums.reduce((all, row) => [...all, ...row], []);
        return all.length === r * c ? new Array(r).fill(0).map((row, m) => all.slice(m * c, m * c + c)) : nums;
    };
    

Log in to reply
 

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