48. Rotate Image
前言
嗯,今天国庆节哦。
最近碰上了两道难度为困难的题,做的自己有点怀疑人生,整天无精打采的。首先是谷歌那道面试题,Super Egg Drop ,这题我就压根没看懂啥意思,最后大体上明白了应该就是给你几个鸡蛋,你要用手里的鸡蛋确定这个特殊的F层楼在第几层,你要一层层的扔鸡蛋,最后就是无论这个F是第几层,你要用你手里的鸡蛋都能确定的最小的移动步数(不过我还是怀疑我没有看懂,所以就没在做了)。其次是一个 Split Array With Same Average ,这题不光需要你的编程知识,还需要简单的数学推论,最后我能学到的就是
如果数组能划分为两个均值相等的数组,那么子数组的平均数和该数组的是相等的。
好了,来看看今天的题目吧:
描述
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Note:
You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
原地顺时针旋转一个矩阵
ac代码
/**
* @param {number[][]} matrix
* @return {void} Do not return anything, modify matrix in-place instead.
*/
var rotate = function(matrix) {debugger;
let L = matrix.length,
circle = L*4 - 4,
row = L,
col = L;
let startIndex = 0;//是开始的坐标,也是当前开始的行数
while( circle > 1 ){
let nextValue,
curCol = curRow = startIndex;
for(let i = 0 ;i < row -1;i++ ){
for( let iterator = 0; iterator < circle ;iterator++){
// 下
if( curCol == (col+startIndex-1) && curRow !==( row+startIndex-1 ) ){
let temp = nextValue;
nextValue=matrix[curRow+1][curCol];
matrix[curRow+1][curCol] = temp;
curRow++;
continue;
}
// 左
if( curRow ==( row+startIndex-1 ) && ( curCol !== startIndex ) ){
let temp = nextValue;
nextValue=matrix[curRow][curCol-1];
matrix[curRow][curCol-1] = temp;
curCol--;
continue;
}
// 上
if( ( curCol == startIndex ) && ( curRow !== startIndex ) ){
let temp = nextValue;
nextValue=matrix[curRow-1][curCol];
matrix[curRow-1][curCol] = temp;
curRow--;
if( curRow == startIndex ){
nextValue = undefined;
break;
}
continue;
}
// 右
if( typeof (nextValue) !== 'undefined' ){
let temp = nextValue;
nextValue=matrix[curRow][curCol+1];
matrix[curRow][curCol+1] = temp;
curCol++;
}else{
nextValue = matrix[curRow][curCol+1];
matrix[curRow][curCol+1] = matrix[curRow][curCol];
curCol++;
}
}
}
row -=2;
col -= 2;
circle = 4 * ( row-1 );
startIndex++;
}
};思路
我的思路是把这个矩阵看成一圈一圈的方圈,实际上旋转90度就是把每个圈转 (圈长度 -1)次,
从外向里依次旋转
像贪吃蛇游戏一样,真的
既然是游戏
旋转的时候就是各种边界值的判定啦
有个小技巧是要把接下来旋转的值保存一下
就酱

浙公网安备 33010602011771号