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?
public class Solution {
public void rotate(int[][] matrix) {
int n = matrix.length;
// let us trust that it is n by n
int start = 0, end = n-1;
while(start < end){
for(int i=start; i<end; i++){
int tmp = matrix[start][i];
matrix[start][i] = matrix[end+start-i][start];
matrix[end+start-i][start] = matrix[end][end+start-i];
matrix[end][end+start-i] = matrix[i][end];
matrix[i][end] = tmp;
}
start++;
end--;
}
}
}
easy problem.
time complexity is O(n^2)
space complexity is O(1)