今日算法:旋转数组
*题目:*由 N × N 矩阵表示的图像,其中每个像素的大小为 4 字节。请你设计一种算法,将图像旋转 90 度。
示例: 给定matrix = [ [1,2,3], [4,5,6], [7,8,9] ],原地旋转后,输出[ [7,4,1], [8,5,2], [9,6,3] ]
思路分析: 输出的数组,在原来数组反转的基础上,从原来数组的行变成了列
所以,在写代码的时候,围绕这个思路展开就可以了
var rotate = function(list){
let result = []
if(list.length == 0 && !list){
return result
}
list = list.reverse()
for(let i=0;i<list.length;i++){
let item = list[i]
for(let j=0;j<item.length;j++){
if(result.length < list.length){
result[j] = [item[j]]
} else {
result[j].push(item[j])
}
}
}
return result
}
这种方法,占用了额外的空间。 如果不占用额外的空间呢?暂时没想到。。想到后再补充。