题目如下:
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?
分析如下:
首先沿着对角线(左上->右下)方向翻折,然后沿着中轴方向翻折。
我的代码:
/* [1][2] [3][1] [3][4] -----> [4][2] [1][2] 沿对角线翻折 [1][3] 沿中轴翻折 [3][1] [3][4] -----> [2][4] ------> [4][2] */ //257 ms public class Solution { public void rotate(int[][] matrix) { for (int i = 0; i < matrix.length; ++i) { for (int j = i + 1; j < matrix[i].length; ++j) { int temp = matrix[i][j]; matrix[i][j] = matrix[j][i]; matrix[j][i] = temp; } } for (int i = 0; i < matrix.length; ++i) { for (int j = 0; j < matrix[i].length/2; ++j) { int temp = matrix[i][j]; // BUG1 indexOutOfBound Exception //matrix[i][j] = matrix[i][matrix[i].length - j]; //matrix[i][matrix[i].length - j] = temp; matrix[i][j] = matrix[i][matrix[i].length - j - 1]; matrix[i][matrix[i].length - j - 1] = temp; } } } }