-
Notifications
You must be signed in to change notification settings - Fork 634
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
剑指Offer&Bigo:旋转矩阵 #57
Comments
思路: 按对角线反转后再逐行倒序
/**
* @param {number[][]} matrix
* @return {void} Do not return anything, modify matrix in-place instead.
*/
var rotate = function(matrix) {
const n = matrix.length;
//对角线反转 0,0 n-1,n-1
for(let i = 0; i < n; i++) {
for(let j = 0; j < i; j++) {
swap(matrix, [i, j], [j, i]);
}
}
//中线左右反转
for(let i = 0; i < n; i++) {
for(let j = 0; j < n / 2; j++) {
swap(matrix, [i, j], [i, n - 1 - j]);
}
}
function swap(matrix, [x1, y1], [x2, y2]) {
const tmp = matrix[x1][y1];
matrix[x1][y1] = matrix[x2][y2];
matrix[x2][y2] = tmp;
}
}; |
function rotateMatrix(mat) {
const len = mat.length
for(let i = 0;i < len;i ++) {
for (let j = i;j < len;j ++) {
let tmp = mat[i][j]
mat[i][j] = mat[j][i]
mat[j][i] = tmp
}
}
for(let i = 0;i< len;i ++) {
for(let j = 0;j < Math.floor(len / 2);j ++) {
let tmp = mat[i][j]
mat[i][j] = mat[i][len - j - 1]
mat[i][len - j - 1] = tmp
}
}
} |
const fun = (arr) => {
for(let i=0,len=arr.length;i<len;i++){
for(let j=i;j<len;j++){
const temp = arr[i][j]
arr[i][j] = arr[j][i]
arr[j][i] = temp
}
}
arr.forEach(val=>{
val.reverse()
})
} |
const rotate = (matrix) =>{
for(let i = 0; i < matrix.length; i++){
for (let j = i; j < matrix[i].length; j++){
[matrix[i][j],matrix[j][i]] = [matrix[j][i],matrix[i][j]]
}
}
matrix.forEach(row=> row.reverse())
}; |
思路:
var rotate = function(matrix) {
const n = matrix[0].length
for(let i = 0 ;i<=(n/2-1);i++){
for(let j = i; j<n-i-1; j++){
[matrix[i][j], matrix[j][n-i-1], matrix[n-i-1][n-j-1], matrix[n-j-1][i]] = [matrix[n-j-1][i], matrix[i][j], matrix[j][n-i-1], matrix[n-i-1][n-j-1]]
}
}
return matrix
}; |
// 思路:先转置后反转
|
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
给你一幅由
N × N
矩阵表示的图像,其中每个像素的大小为 4 字节。请你设计一种算法,将图像旋转 90 度。不占用额外内存空间能否做到?
示例 1:
示例 2:
附赠leetcode地址:leetcode
The text was updated successfully, but these errors were encountered: