Rotate Image
来源:互联网 发布:网络诈骗揭秘 编辑:程序博客网 时间:2024/06/06 19:46
LeetCode中Image的rotate问题
旋转一张图片,其实不难,但是也有点意思,上题咯~
https://leetcode.com/problems/rotate-image/
原题
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?
翻译:给你一个n*n的矩阵,你能顺时针将其旋转90度吗。追问:可以不使用额外的空间吗?
为题分析
看到这个问题,让我想到了我在array的rotate那一题中的思路,把a送到该去的位置,然后将该位置上的元素送到它该去的位置,最后循环到起始位置,利用整个矩阵的中心,我只要先旋转整个第一行,然后第二行的2到n-1的元素,第三行的3到n-2的元素…
如图:
我们先旋转红色的元素,然后旋转黄色的元素,然后旋转蓝色的元素。比如对于A位置,将A送到B,B位置的送到C,C送到D,D送到A,这也是为什么第一行最后一个元素不需要进行旋转。
上代码:
public void rotate(int[][] matrix) { int length = matrix.length; if(length < 2) { return; } double core = 0; //对于n为基数或者偶数,计算旋转的中心坐标 core = length % 2 == 0 ? length/2 - 0.5 : length/2; for(int i = 0; i < length/2; i++) { for(int j = i; j < length - i - 1; j++ ) { rotate(matrix, i, j, core); } } return;}//图中A-B-C-D的一次旋转操作,core是中心坐标,x和y是该店的横纵坐标public void rotate(int[][] matrix, int x, int y, double core){ int temp = matrix[x][y]; double nextX = x; double nextY = y; for(int i = 0; i < 4; i++) { double tempY = nextY; nextY = 2*core - nextX; nextX = tempY; int newTemp = matrix[(int)nextX][(int)nextY]; matrix[(int)nextX][(int)nextY] = temp; temp = newTemp; }}
这里面的坐标计算不太直观,自己画图分析分析吧,哈哈,接下来我们就要研究研究rotate数组中的查找问题咯,我觉得接下俩的四个问题主要训练的还是分而治之的思维方式。
0 0
- Rotate Image
- Rotate Image
- Rotate Image
- Rotate Image
- Rotate Image
- Rotate Image
- Rotate Image
- Rotate Image
- Rotate Image
- Rotate Image
- Rotate Image
- Rotate Image
- Rotate Image
- Rotate Image
- Rotate Image
- Rotate Image
- Rotate Image
- Rotate Image
- 黑马程序员—IOS基础之OC—ARC和Category
- c语言实现二分搜索算法
- Maven安装,Eclipse创建项目过程
- Improving Your Code With Android Support Annotations(译文)
- 可数集合与不可数集合
- Rotate Image
- λ演算
- JAVA线程中ThreadLocal和volatile的说明
- HDU水题 统计元音
- HDU 1237 简单计算器(栈)
- N的M次方最右边的数字
- 程序员必读书单 1.0
- POJ 1068 Parencodings(暴力枚举)
- 对角化原理和停机问题