将矩阵顺时针旋转90度 leetCode:Rotate Image
来源:互联网 发布:搜索引擎优化实战培训 编辑:程序博客网 时间:2024/05/28 11:48
一个图像用矩阵表示,将这个图像顺时针旋转90度,也就是将矩阵顺时针旋转90度。算法要求不使用额外的空间复杂度,in-place算法。
观察了一下矩阵的转置,发现可以通过以此交换矩阵两行,然后再求转置的方式获得。思路如下:
1、设矩阵有n行,则分别将i=0.1....(n/2-1)行与n-1-i行交换。(看上去有点像上半区与下半区交换)
2、求转置,旋转完成。
代码如下:
package leetCode;public class Solution {//交换矩阵的两行public void swap2line(int[][] matrix,int i,int j){int col = matrix[i].length;int temp;for(int k=0;k<col;k++){temp = matrix[i][k];matrix[i][k] = matrix[j][k];matrix[j][k] = temp;}} public void rotate(int[][] matrix) { if(matrix.length==0 || matrix[0].length==0){ return; } int row = matrix.length; int halfRow = matrix.length/2; for(int i=0;i<halfRow;i++){//交换行 swap2line(matrix,i,row-1-i); } //求转置 for(int i=0,j=0;i<row;i++,j++){ for(int k=i+1;k<row;k++){ int temp = matrix[i][k]; matrix[i][k] = matrix[k][j]; matrix[k][j] = temp; } } } public void display(int[][] matrix){ for(int i=0;i<4;i++){ for(int j=0;j<4;j++){ System.out.print(matrix[i][j]+" "); } System.out.println(); } System.out.println(); } public static void main(String[] args) { Solution s = new Solution(); int[][] matrix = { {1,2,3,4}, {5,6,7,8}, {9,10,11,12}, {13,14,15,16} }; s.rotate(matrix); s.display(matrix);}}
0 0
- 将矩阵顺时针旋转90度 leetCode:Rotate Image
- 方形矩阵顺时针旋转90度 Rotate Image
- Rotate Image 数组顺时针旋转90度
- LeetCode-48-Rotate Image 矩阵旋转90
- [leetcode 48] Rotate Image--------矩阵旋转90度
- LeetCode-----48. Rotate Image(二维矩阵旋转90度)
- Rotate Image 旋转矩阵 @LeetCode
- LeetCode——Rotate Image(二维数组顺时针旋转90度)
- leetcode rotate-image(90°旋转矩阵)
- 【LeetCode】48 Rotate Image && 【九度】题目1164:旋转矩阵
- LeetCode Rotate Image(矩阵的旋转)
- leetcode-48 Rotate Image 旋转矩阵
- leetcode 48. Rotate Image-矩阵旋转
- leetcode 48. Rotate Image(矩阵旋转)
- leetcode 48. Rotate Image 矩阵旋转
- 【旋转矩阵】Rotate Image
- Rotate Image 矩阵旋转90度,没有额外空间
- 矩阵顺时针旋转90度
- hdu 3971
- 中兴f402 412等破解超级密码、破解用户限制、关闭远程控制、恢复路由器拨号
- 学习与实践Cadence总结
- Ubuntu 15.04 clang++ 3.6 编译boost 1.59/1.55
- 山峰
- 将矩阵顺时针旋转90度 leetCode:Rotate Image
- Convert Sorted List to Binary Search Tree
- Java中的进制转换,练习
- linux 几个简单shell脚本demo
- UIAlertView提示控件和UIActionSheet的使用
- CodeForces-327A Flipping Game
- ant 中 if else
- 你不知道的JavaScript--Item25 创建对象(类)的8种方法总结
- IOS9自定义UIWindow被键盘盖住(在键盘下面)解决方法