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?
Could you do this in-place?
Solution: 基本思路是把图片分为行数/2层,然后一层层进行旋转,每一层有上下左右四个列,然后目标就是把上列放到右列,右列放到下列,下列放到左列,左列放回上列,中间保存一个临时变量即可。因为每个元素搬运的次数不会超过一次,时间复杂度是O(n^2),空间复杂度是O(1)。
public class Solution { public void rotate(int[][] matrix) { if(matrix == null) return; int len = matrix.length; int layer = len / 2; for(int i = 0; i < layer; i++) { for(int j = i; j < len-i-1; j++) { int temp = matrix[i][j]; matrix[i][j] = matrix[len-1-j][i]; matrix[len-1-j][i] = matrix[len-1-i][len-1-j]; matrix[len-1-i][len-1-j] = matrix[j][len-1-i]; matrix[j][len-1-i] = temp; } } } }
No comments:
Post a Comment