这种题目有了正确的方法就能简单很多。这道题目是先做对角线的交换,然后上下交换。要注意的是,如果对角线交换,等号两边的i和j肯定是交换的(m[i][j]和m[j][i])
public class Solution { public void rotate(int[][] matrix) { int len = matrix.length; for (int i = 0; i < len; i++) { for (int j = 0; j < len-i; j++) { int tmp = matrix[i][j]; matrix[i][j] = matrix[len-j-1][len-i-1]; matrix[len-j-1][len-i-1] = tmp; } } for (int i = 0; i < len/2; i++) { for (int j = 0; j < len; j++) { int tmp = matrix[i][j]; matrix[i][j] = matrix[len-i-1][j]; matrix[len-i-1][j] = tmp; } } } }