forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0048-rotate-image.js
More file actions
79 lines (67 loc) · 1.95 KB
/
0048-rotate-image.js
File metadata and controls
79 lines (67 loc) · 1.95 KB
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/**
* Time O(ROWS * COLS) | Space O(1)
* https://leetcode.com/problems/rotate-image/
* @param {number[][]} matrix
* @return {void} Do not return anything, modify matrix in-place instead.
*/
var rotate = (matrix) => {
transpose(matrix); /* Time O(ROWS * COLS) */
reflect(matrix); /* Time O(ROWS * COLS) */
};
var transpose = (matrix) => {
const rows = matrix.length;
for (let row = 0; row < rows; row++) {
/* Time O(ROWS) */
for (let col = row + 1; col < rows; col++) {
/* Time O(COLS) */
swap1(matrix, row, col);
}
}
};
var swap1 = (matrix, row, col) =>
([matrix[row][col], matrix[col][row]] = [
matrix[col][row],
matrix[row][col],
]);
var reflect = (matrix) => {
const rows = matrix.length;
for (let row = 0; row < rows; row++) {
/* Time O(ROWS) */
for (let col = 0; col < rows / 2; col++) {
/* Time O(COLS) */
const reflection = rows - col - 1;
swap2(matrix, row, col, reflection);
}
}
};
var swap2 = (matrix, row, col, reflection) =>
([matrix[row][col], matrix[row][reflection]] = [
matrix[row][reflection],
matrix[row][col],
]);
/**
* Time O(ROWS * COLS) | Space O(1)
* https://leetcode.com/problems/rotate-image/
* @param {number[][]} matrix
* @return {void} Do not return anything, modify matrix in-place instead.
*/
var rotate = (matrix) => {
reverse(matrix); /* Time O(ROWS) */
transpose(matrix); /* Time O(ROWS * COLS) */
};
var reverse = (matrix) => matrix.reverse();
var transpose = (matrix) => {
const rows = matrix.length;
for (let row = 0; row < rows; row++) {
/* Time O(ROWS) */
for (let col = 0; col < row; col++) {
/* Time O(COLS) */
swap(matrix, row, col);
}
}
};
var swap = (matrix, row, col) =>
([matrix[row][col], matrix[col][row]] = [
matrix[col][row],
matrix[row][col],
]);