Last active
April 26, 2021 19:14
-
-
Save RAAbbott/065194aee8417caf42c785302103a42f to your computer and use it in GitHub Desktop.
Rotate a 2d n x n matrix IN PLACE
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param {number[][]} matrix | |
* @return {void} Do not return anything, modify matrix in-place instead. | |
*/ | |
// Faster than 80.52% of submissions, less than 40.77% memory usage than other submissions | |
const rotate = function(matrix) { | |
const len = matrix.length | |
// Start with this: | |
// [1,2,3] | |
// [4,5,6] | |
// [7,8,9] | |
for (let j = len - 1; j >= 0; j--) { | |
for (let i = j - 1; i >= 0; i--) { | |
matrix[j].push(matrix[i].pop()) | |
} | |
} | |
// Now it's this: | |
// [ 1 ] | |
// [ 4, 5, 2 ] | |
// [ 7, 8, 9, 6, 3 ] | |
for (let j = 0; j < len - 1; j++) { | |
for (let i = j + 1; i < len; i++) { | |
matrix[j].unshift(matrix[i].shift()) | |
} | |
} | |
// After final nested for loop, it's this: | |
// [7,4,1] | |
// [8,5,2] | |
// [9,6,3] | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment