LeetCode——Rotate Image(二维数组顺时针旋转90度)
2014-10-07 15:18
447 查看
问题: 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?
分析: 二维数组a
顺时针旋转90度,要解决这个问题,无疑,第一件事儿就是找规律。
当n=1时,不用动了。
当n=2时,
![](https://oscdn.geek-share.com/Uploads/Images/Content/202009/06/fde799255da6cccf62f13f034c35c7ac.png)
旋转之后变为
![](https://oscdn.geek-share.com/Uploads/Images/Content/202009/06/e215b538d583d8c9c9ecd45504984295.png)
有:
a[0][0] = a[1][0]
a[1][0] = a[1][1]
a[1][1] = a[0][1]
a[0][1] = a[0][0]
在这里我们初步总结规律为:a[i][j] = a[n-1-j][i]
当n=4,5,……时也是满足的。
到这里,如果不考虑空间复杂的度的话,我们已经可以解决这个问题了,只需要再构建一个二维数组b
,利用公式b[i][j] = a[n-1-j][i],就ok了,代码如下:
public void rotate(int[][] matrix) { int n = matrix.length; int[][] m = new int ; for(int row=0;row<n;row++){ for(int col=0;col<n;col++){ m[row][col] = matrix[n-1-col][row]; } } //再赋值回matrix,注意java是形参是引用传递 for(int row=0;row<n;row++){ for(int col=0;col<n;col++){ matrix[row][col] = m[row][col]; } } }
但是在这里,题目中也要求了,就在原数组中,应该怎么旋转?
接着上面的分析,以n=3为例:
我们把焦点放在一个元素的旋转上,可以看出要在员数组中旋转,在不丢失数据的情况下,每个值的要旋转会“波及”4个数,以1为例波及到了1,3,7,9,每个数旋转要不丢失数据就要考虑如何让这个4个数都得以保留
前边总结了规律a[i][j] = a[n-1-j][i],分析每组被波及的数,我们可以得出这里波及的4了数其实就是
a[i][j]
a[n-1-j][i]
a[n-1-i][n-1-j]
a[n-1-(n-1-j)][n-1-i]=a[j][n-1-i]
所以这里需要引入一个临时变量temp就可以解决这4个数的顺时针交换,如:
int temp = matrix[i][j]; matrix[i][j] = matrix[n-1-j][i]; matrix[n-1-j][i] = matrix[n-1-i][n-1-j]; matrix[n-1-i][n-1-j] = matrix[j][n-1-i]; matrix[j][n-1-i] = temp;
把焦点放在一个元素上,数交换的问题解决了,
那么现在我们把焦点回到整个二维数组上来,每个数的旋转会波及4个数,相当于用上面的方法,每旋转一个数,就把一组的4个数都旋转了,
所以现在的问题就是如何才能完整的把所有的数都旋转90度且不会多旋转,继续分析吧,
n=1时,不需旋转。
n=2时,
n=3时,
n=4时,
n=5时,
大致可以总结出这么一个规律:
对于要旋转的数a[i][j]满足,
i<n/2
且
i<=j<n-1-i
至此问题终于完美解决了。。
代码如下:
public class Solution {
public void rotate(int[][] matrix) {
int n = matrix.length;
int limit = (n-1)/2;
for(int i=0;i<= limit; i++){
for(int j=i;j<n-1-i;j++){
int temp = matrix[i][j]; matrix[i][j] = matrix[n-1-j][i]; matrix[n-1-j][i] = matrix[n-1-i][n-1-j]; matrix[n-1-i][n-1-j] = matrix[j][n-1-i]; matrix[j][n-1-i] = temp;
}
}
}
}
相关文章推荐
- LeetCode——Rotate Image(二维数组顺时针旋转90度)
- 方形矩阵顺时针旋转90度 Rotate Image
- Rotate Image 二维数组旋转90度
- [leetcode 48] Rotate Image--------矩阵旋转90度
- [LeetCode] Rotate Image n-by-n矩阵顺时针旋转
- LeetCode-----48. Rotate Image(二维矩阵旋转90度)
- leetcode 48. Rotate Image 矩阵旋转
- LeetCode 48. Rotate Image(旋转图片)
- [LeetCode]—Rotate Image 矩阵90度翻转
- leetcode之图像旋转(Rotate Image)
- [Leetcode] rotate image 旋转图片
- Rotate Image(二位数组顺时针旋转)
- LeetCode 48. Rotate Image(旋转)
- 矩阵旋转系列之【LeetCode】Rotate Image && 【九度】题目1164:旋转矩阵
- LeetCode Rotate Image旋转图像
- Rotate Image(二位数组顺时针旋转)
- Leetcode刷题记——48. Rotate Image(旋转图像)
- [LeetCode] Rotate Image 旋转图像
- leetcode解题之48. Rotate Image java版(旋转图像)
- LeetCode | Rotate Image(旋转图像)