A few JavaScript solutions


  • 0

    The intuitive way:

    var matrixReshape = function(nums, h, w) {
        const m = nums.length, n = nums[0].length;
        if (m * n !== h * w) return nums;
        const res = [];
        for (let i = 0, r = 0; r < m; r++) {
            for (let c = 0; c < n; c++, i++) {
                let rr = Math.floor(i / w);
                if (!res[rr]) res.push([]);
                res[rr].push(nums[r][c]);
            }
        }
        return res;
    };
    

    One loop:

    var matrixReshape = function(nums, h, w) {
        const m = nums.length, n = nums[0].length;
        if (m * n !== h * w) return nums;
        const res = [];
        for (let i = 0; i < m * n; i++) {
            let r = Math.floor(i / w);
            if (!res[r]) res.push([]);
            res[r].push(nums[Math.floor(i / n)][i % n]);
        }
        return res;
    };
    

    Two-liner:

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

Log in to reply
 

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