cci-Q1.6 矩形90度旋转
来源:互联网 发布:北京雾霾 知乎 编辑:程序博客网 时间:2024/05/08 22:43
原文:
Given an image represented by an NxN matrix, where each pixel in the image is 4 bytes, write a method to rotate the image by 90 degrees. Can you do this in place?
译文:
一张图像表示成NxN的矩阵,图像中每个像素是4个字节,写一个函数把图像旋转90度。 你能原地进行操作吗?(即不开辟额外的存储空间)
N*N矩形,旋转90度,直观来看就是最外圈进行旋转,一层一层往里再进行旋转。
public static int[][] rotate(int[][] matrix, int n) { for (int layer = 0; layer < n / 2; layer++) { int first = layer; int last = n - first - 1; for (int i = first; i < last; i++) { int offset = i - first; //Save top int top = matrix[first][i]; // left->top matrix[first][i] = matrix[last - offset][first]; //bottom->left matrix[last - offset][first] = matrix[last][last - offset]; //right->bottom matrix[last][last - offset] = matrix[i][last]; //top->right matrix[i][last] = top; } } return matrix; }
junit testcase
@Test public void testRotate() { System.out.println("rotate"); int[][] test = {{1, 2}, {3, 4}}; int[][] expected = {{3, 1}, {4, 2}}; assertArrayEquals(expected, q1_6.rotate(test, 2)); int[][] test1 = {{1}}; int[][] expected1 = {{1}}; assertArrayEquals(expected1, q1_6.rotate(test1, 1)); int[][] test2 = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}; int[][] expected2 = {{13, 9, 5, 1}, {14, 10, 6, 2}, {15, 11, 7, 3}, {16, 12, 8, 4}}; assertArrayEquals(expected2, q1_6.rotate(test2, 4)); int[][] test3 = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; int[][] expected3 = {{7, 4, 1}, {8, 5, 2}, {9, 6, 3}}; assertArrayEquals(expected3, q1_6.rotate(test3, 3)); }
- cci-Q1.6 矩形90度旋转
- cci-Q1.8 调用一次子字符串判断确认s2是否为s1的旋转字符
- cci-Q1.2 C风格字符串反转
- cci-Q1.3 字符数组去重
- cci-Q1.5 空格替换为%20
- cci-Q1.7 二维数组置0
- CCI 1.6 旋转矩阵
- cci-Q1.1 判断字符串中字符是否唯一
- cci-Q1.4 判断两个字符串是否为变位词
- 【Cracking the coding interview】Q1.6(旋转矩阵)
- Q1.6
- 矩形旋转
- openglesForC++矩形旋转
- 旋转矩形框
- Q1
- Q1.6 To rotate a image by 90 degress.
- 【Cracking the coding interview】Q1.8(旋转字符串)
- android 矩形变换 图像旋转
- linux uniq命令参数及用法详解
- 关于log4j将日志文件发送至邮箱的例子
- nyist-480
- ubuntu Samba服务安装与配置
- 实习笔记(防丢)
- cci-Q1.6 矩形90度旋转
- 关于php_apc的一个疑问
- linux fork函数浅析
- Linux下autoconf和automake使用
- 链表的实现
- 文字接口联机服务器:ssh服务器
- 'sqlplus' 不是内部或外部命令,也不是可运行的程序
- 对页游《小兵大战》服务器DM内存溢出的排错过程总结
- linux2.6内核移植zc301摄像头时 kernel BUG at arch/arm/mm/dma-mapping.c:409!..的解决方法