Rotate Image
来自 <https://leetcode.com/problems/rotate-image/>
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Follow up:
Could you do this in-place?
题目解读
给定一个n x n的2D矩阵代表一张图片,将图片旋转90度(顺时针方向)。
你能在原地解决吗?
解析:将二维矩阵先第0行与第n-1行、第1行与第n-2行…进行交换,然后按照主对角线进行交换。可得到旋转90°的效果
Java代码
public class Solution {
public void rotate(int[][] matrix) {
int low = 0;
int high = matrix.length-1;
int temp = 0;
//第一次进行上下交换
while(low<high) {
for(int i=0; i<matrix.length; i++){
temp = matrix[low][i];
matrix[low][i] = matrix[high][i];
matrix[high][i] = temp;
}
low++;
high--;
}
//第二次按照主对角线进行交换
for(int i=0; i< matrix.length; i++) {
for(int j=i; j<matrix.length; j++) {
temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
}
}
代码性能