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?
Could you do this in-place?
Solution 1: Pay attention to the math, two loops. O(n^2)
public class Solution {
public void rotate(int[][] matrix) {
int n=matrix.length;
if (n<=1) return;
int lo=0, hi=n-1;
while (lo<hi) {
for (int i=lo; i<hi; i++) {
int temp=matrix[lo][i];
matrix[lo][i]=matrix[hi+lo-i][lo];
matrix[hi+lo-i][lo]=matrix[hi][hi+lo-i];
matrix[hi][hi+lo-i]=matrix[i][hi];
matrix[i][hi]=temp;
}
lo++;
hi--;
}
}
}
没有评论:
发表评论