leetcode-48 Rotate Image 旋转矩阵
2015-10-24 10:23
344 查看
《程序员面试金典》P114 题目1.6
问题描述:
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?
问题分析:
题目要求旋转一个二维正方形数组矩阵90度,且空间复杂度为O(1)
![](https://img-blog.csdn.net/20151024102222822)
程序需要做的就是一层一层进行遍历转换,
伪码:
假定top[i]对应的
行row = layer; 列 column = j;则:
Left: row = n – 1 – j; column = layer;
Bottom: row = n – 1 – layer; j = n – 1 – j;
Right: row = j; column = n – 1 – layer;
代码:
问题描述:
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?
问题分析:
题目要求旋转一个二维正方形数组矩阵90度,且空间复杂度为O(1)
程序需要做的就是一层一层进行遍历转换,
伪码:
for i = 0 : n – 2 (注意此边界 n – 1 - 1) int temp = top[i]; top[i] = left[i]; left[i] = right[i]; right[i] = temp;
假定top[i]对应的
行row = layer; 列 column = j;则:
Left: row = n – 1 – j; column = layer;
Bottom: row = n – 1 – layer; j = n – 1 – j;
Right: row = j; column = n – 1 – layer;
代码:
public class Solution { public void rotate(int[][] matrix) { int n = matrix.length; for (int layer = 0; layer < n / 2; layer ++) { // 注意旋转的边界,最后一个元素要注意留下来 for (int j = layer; j < n - 1 - layer; j ++) { int temp = matrix[layer][j]; matrix[layer][j] = matrix[n - 1 - j][layer]; matrix[n - 1 - j][layer] = matrix[n - 1 - layer][n - 1 - j]; matrix[n - 1 - layer][n - 1 - j] = matrix[j][n - 1 - layer]; matrix[j][n - 1 - layer] = temp; } } } }
相关文章推荐
- paint类,path用法
- NSOperation 之 Block循环引用——以及nil Nil NULL [NULL null]的区别
- 详说清除浮动
- android Fragment
- 20151024_temp
- 记录Android项目中遇到的小问题
- 针对Font 'STSongStd-Light' with 'UniGB-UCS2-H' is not recognized.的问题的解决
- 黑苹果懒人版10.10.5驱动HD4600
- Linux 系统信息分析
- 数据库引起的死锁及死锁的定义
- MyBatis中插入并返回主键
- DrawingControl控件在Add Page时报故障的问题
- 【SSH项目实战】国税协同平台-6.POI导出用户列表
- mysql驱动包添加, 通过mysql connector 连接数据库
- win7权限如何设置最高管理员权限呢?
- 【Android】安卓SDK出错的解决办法
- redis、memcache、mongoDB 对比
- ZOJ-3593 One Person Game
- WPF 札记
- CentOS7 添加用户到 sudoers