This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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? | |
Common question in interview, pay attention to index | |
public class Solution { | |
public void rotate(int[][] matrix) { | |
if( matrix==null ||matrix.length==0){ | |
return; | |
} | |
int layer=matrix.length/2; | |
for (int l=0; l<layer; l++){ | |
int st=l; | |
int ed=matrix.length-l-1; | |
for (int i=st; i<ed; i++){ | |
// pay attention here, the offset is distance from i to st | |
// so because of symmetry reason, we should calculate the distance from ed | |
// which is ed-offset | |
int offset=i-st; | |
int top=matrix[st][i]; | |
// left to top | |
matrix[st][i]=matrix[ed-offset][st]; | |
// bottom to left | |
matrix[ed-offset][st]=matrix[ed][ed-offset]; | |
// right to bottom | |
matrix[ed][ed-offset]=matrix[i][ed]; | |
// top to right | |
matrix[i][ed]=top; | |
} | |
} | |
} | |
} |
No comments:
Post a Comment