풀이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 에선 사용 불가능하다.
'알고리즘 > LeetCode' 카테고리의 다른 글
[Leetcode][자바스크립트][Easy] 383. Ransom Note (0) | 2022.01.10 |
---|---|
[Leetcode][자바스크립트][Easy] 387. First Unique Character in a String (0) | 2022.01.10 |
[Leetcode][자바스크립트][Easy] 121. Best Time to Buy and Sell Stock (0) | 2022.01.08 |
[Leetcode][자바스크립트][Easy] 350. Intersection of Two Arrays II (0) | 2022.01.08 |
[Leetcode][자바스크립트][Easy] 88. Merge Sorted Array (0) | 2022.01.06 |
댓글