原题链接在这里: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?
题解:
顺时针旋转矩阵,举例子找规律。
matrix[i][j] 由 matrix[n-1-j][i]替换.
若是需要做成in-space, 那么相当于把矩阵拆成四块,第一块值保留,然后四块依次赋值,最后一块等于保留值。
但需要注意循环中i,j中必有一个参数是小于等于Math.ceil(n/2.0), 否则中间点没有改值.
Time Complexity: O(m*n). Space: O(1).
AC Java:
1 public class Solution { 2 public void rotate(int[][] matrix) { 3 if(matrix == null || matrix.length == 0 || matrix[0].length == 0){ 4 return; 5 } 6 int n = matrix.length; 7 8 for(int i = 0; i<n/2; i++){ 9 for(int j = 0; j<Math.ceil(n/2.0); j++){ //注意 2 要换成 double型, 2.0 10 int temp = matrix[i][j]; 11 matrix[i][j] = matrix[n-1-j][i]; 12 matrix[n-1-j][i] = matrix[n-1-i][n-1-j]; 13 matrix[n-1-i][n-1-j] = matrix[j][n-1-i]; 14 matrix[j][n-1-i] = temp; 15 } 16 } 17 } 18 }