您的位置:首页 > 职场人生

面试题6 将一个n*n图像矩阵顺时针旋转90°

2015-12-26 06:57 549 查看
题目: 用一个 n*n 的 int 矩阵代表一个图像 原址将这个图像旋转九十度

思路: 先将所有行倒序 就是第一行变成最后一行 然后第二行变成倒数第二行 以此类推 然后根据对角线将对称的位置对换 就可以了 代码如下

public void mySolution(int[][] image){
if(!isSquareMatrix(image))  return;

int n = image.length; //n is the size of the square matrix

//reverse the matrix by row (so first row become the last and so on)
for(int i=0, j=n-1; i<j; i++, j--){
int[] temp = image[i];
image[i] = image[j];
image[j] = temp;
}

//swap entries against diagonal
for(int i=0; i<n-1; i++){
for(int j=i+1; j<n; j++)  swap(image, j,i, i,j);
}

private void swap(int[][] a, int row1, int col1, int row2, int col2){
int temp = a[row1][col1];
a[row1][col1] = a[row2][col2];
a[row2][col2] = temp;
}


该方法的时间复杂度和空间复杂度均为 O(n)

另一种思路: 由最外层开始一层一层旋转九十度 将上面的变成对应位置右面的 将对应位置右面的变成下面 以此类推 代码如下

public void goodSolution(int[][] matrix){
if(!isSquareMatrix(matrix)) return;

int n = matrix.length;

for(int layer=0; layer<n/2; ++layer){
int first = layer;
int last = n-layer-1;

for(int i=first; i<last; ++i){
int offset = i-first;

int top = matrix[first][i];
matrix[first][i] = matrix[last-offset][first];
matrix[last-offset][first] = matrix[last][last-offset];
matrix[last][last-offset] = matrix[i][last];
matrix[i][last] = top;
}
}
}


该方法更难思考一些 但是效率最高 时间复杂度和空间复杂度也均为 O(n)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: