Skip to content

Commit a8b5836

Browse files
committed
Add solution #566
1 parent 293abff commit a8b5836

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@
6262
459|[Repeated Substring Pattern](./0459-repeated-substring-pattern.js)|Easy|
6363
541|[Reverse String II](./0541-reverse-string-ii.js)|Easy|
6464
565|[Array Nesting](./0565-array-nesting.js)|Medium|
65+
566|[Reshape the Matrix](./0566-reshape-the-matrix.js)|Easy|
6566
606|[Construct String from Binary Tree](./0606-construct-string-from-binary-tree.js)|Easy|
6667
617|[Merge Two Binary Trees](./0617-merge-two-binary-trees.js)|Easy|
6768
628|[Maximum Product of Three Numbers](./0628-maximum-product-of-three-numbers.js)|Easy|

solutions/0566-reshape-the-matrix.js

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/**
2+
* 566. Reshape the Matrix
3+
* https://leetcode.com/problems/reshape-the-matrix/
4+
* Difficulty: Easy
5+
*
6+
* In MATLAB, there is a handy function called reshape which can reshape an m x n
7+
* matrix into a new one with a different size r x c keeping its original data.
8+
*
9+
* You are given an m x n matrix mat and two integers r and c representing the
10+
* number of rows and the number of columns of the wanted reshaped matrix.
11+
*
12+
* The reshaped matrix should be filled with all the elements of the original
13+
* matrix in the same row-traversing order as they were.
14+
*
15+
* If the reshape operation with given parameters is possible and legal, output
16+
* the new reshaped matrix; Otherwise, output the original matrix.
17+
*/
18+
19+
/**
20+
* @param {number[][]} mat
21+
* @param {number} r
22+
* @param {number} c
23+
* @return {number[][]}
24+
*/
25+
var matrixReshape = function(mat, r, c) {
26+
const flat = mat.flat();
27+
const result = [];
28+
29+
if (flat.length !== r * c) {
30+
return mat;
31+
}
32+
33+
while (flat.length) {
34+
result.push(flat.splice(0, c));
35+
}
36+
37+
return result;
38+
};

0 commit comments

Comments
 (0)