-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0566-reshape-the-matrix.js
More file actions
37 lines (33 loc) · 971 Bytes
/
0566-reshape-the-matrix.js
File metadata and controls
37 lines (33 loc) · 971 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/**
* Reshape The Matrix
* Time Complexity: O(initialRowsLength * initialColsLength)
* Space Complexity: O(newRowsCount * newColsCount)
*/
var matrixReshape = function (mat, r, c) {
const initialRowsLength = mat.length;
const initialColsLength = mat[0].length;
if (initialRowsLength * initialColsLength !== r * c) {
return mat;
}
const outputMatrixForm = Array(r)
.fill(null)
.map(() => []);
let currentFlattenedIndex = 0;
for (
let currentRowIterator = 0;
currentRowIterator < initialRowsLength;
currentRowIterator++
) {
for (
let currentColIterator = 0;
currentColIterator < initialColsLength;
currentColIterator++
) {
const elementValue = mat[currentRowIterator][currentColIterator];
const targetRowPosition = Math.floor(currentFlattenedIndex / c);
outputMatrixForm[targetRowPosition].push(elementValue);
currentFlattenedIndex++;
}
}
return outputMatrixForm;
};