본문 바로가기
알고리즘/LeetCode

[Leetcode][자바스크립트][Easy] 566. Reshape the Matrix

by Benjamin_Choi 2022. 1. 9.

풀이1

/**
 * 566_ReshapeTheMatrix.js
 * Easy
 * https://leetcode.com/problems/reshape-the-matrix/
 */

var matrixReshape = function(mat, r, c) {
    if (mat[0].length * mat.length !== r * c) return mat;

    let temp = [];
    mat.forEach((subArr) => temp = temp.concat(subArr));

    const answer = [[]];

    temp.forEach((val) => {
        if (answer[answer.length - 1].length === c) answer.push([]);
        answer[answer.length - 1].push(val);
    });

    return answer;
};

2중 배열을 1중으로 평탄화하고, 새로운 배열을 넣고 값을 넣되 column 개수만큼 끊어서 넣어준다. 

 

풀이2 - Array.prototype.flat() 활용

/**
 * 566_ReshapeTheMatrix.js
 * Easy
 * https://leetcode.com/problems/reshape-the-matrix/
 */
 
 var matrixReshape = function(mat, r, c) {
    if (mat[0].length * mat.length !== r * c) return mat;

    const flatArr = mat.flat(), answer = [[]];

    flatArr.forEach((val) => {
        if (answer[answer.length - 1].length === c) answer.push([]);
        answer[answer.length - 1].push(val);
    });

    return answer;
};

풀이1 에선 평탄화를 concat 으로 해줬는데, 실제 Array built-in 에 flat() 이 있어서 사용해봤다. IE 에선 사용 불가능하다. 

 

 

 

댓글