力扣-面试题01.07-旋转矩阵

题目:
Rotate Matrix LCCI(medium88)


解题思路:
先以主对角线为轴进行翻转每个数,再以每行中点为轴翻转每行。
//https://leetcode-cn.com/problems/rotate-matrix-lcci/solution/jian-dan-java-yuan-di-shuang-bai-by-sweetiee/


代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public void rotate(int[][] matrix) {
int n = matrix.length;
//先以主对角线为轴进行翻转
for(int i = 0;i<n-1;i++){
for(int j = i+1; j<n;j++){
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
//再以每行中点为轴翻转每行
int mid = n >> 1;
for(int i = 0;i<n;i++){
for(int j = 0;j<mid;j++){
int temp = matrix[i][j];
matrix[i][j] = matrix[i][n-1-j];
matrix[i][n-1-j]=temp;
}
}
}