Link:
https://oj.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?
Time: O(n^2), Space: O(1)
一次过。不用再写。
public class Solution {
public void rotate(int[][] matrix) {
int n = matrix.length;
for(int i = 0; i < n/2; i++){
for(int j = 0; j < n; j++){
int tmp = matrix[i][j];
matrix[i][j] = matrix[n-1-i][j];//n-1-i, not n-i
matrix[n-1-i][j] = tmp;
}
}
for(int i = 0; i < n; i++){
for(int j = i+1; j < n; j++){//j starts from i+1, not 0 (i.e. Upperleft triangle)
int tmp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = tmp;
}
}
}
}